How to strip comma in Python string

PythonStringStrip

Python Problem Overview


How can I strip the comma from a Python string such as Foo, bar? I tried 'Foo, bar'.strip(','), but it didn't work.

Python Solutions


Solution 1 - Python

You want to replace it, not strip it:

s = s.replace(',', '')

Solution 2 - Python

Use replace method of strings not strip:

s = s.replace(',','')

An example:

>>> s = 'Foo, bar'
>>> s.replace(',',' ')
'Foo  bar'
>>> s.replace(',','')
'Foo bar'
>>> s.strip(',') # clears the ','s at the start and end of the string which there are none
'Foo, bar'
>>> s.strip(',') == s
True

Solution 3 - Python

unicode('foo,bar').translate(dict([[ord(char), u''] for char in u',']))

Solution 4 - Python

This will strip all commas from the text and left justify it.

for row in inputfile:
    place = row['your_row_number_here'].strip(', ')

‎ ‎‎‎‎‎ ‎‎‎‎‎‎

Solution 5 - Python

You can use rstrip():

s = s.rstrip(",")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmsampaioView Question on Stackoverflow
Solution 1 - PythoneumiroView Answer on Stackoverflow
Solution 2 - PythonpradyunsgView Answer on Stackoverflow
Solution 3 - PythonmaowView Answer on Stackoverflow
Solution 4 - PythonShalView Answer on Stackoverflow
Solution 5 - PythonTauno ErikView Answer on Stackoverflow