Search code examples
pythonstringstrip

.strip not working in python


I don't really understand the .strip function.

Say I have a string

xxx = 'hello, world'

and I want to strip the comma. Why doesn't

print xxx.strip(',')

work?


Solution

  • str.strip() removes characters from the start and end of a string only. From the str.strip() documentation:

    Return a copy of the string with the leading and trailing characters removed.

    Emphasis mine.

    Use str.replace() to remove text from everywhere in the string:

    xxx.replace(',', '')
    

    For a set of characters use a regular expression:

    import re
    
    re.sub(r'[,!?]', '', xxx)
    

    Demo:

    >>> xxx = 'hello, world'
    >>> xxx.replace(',', '')
    'hello world'