Search code examples
pythonstringstrip

strip(char) on a string


I am trying to strip the characters '_ ' (underscore and space) away from my string. The first code fails to strip anything.

The code for word_1 works just as I intend. Could anyone enlighten me how to modify the first code to get output 'ale'?

word = 'a_ _ le' 

word.strip('_ ')

word_1 = '_ _ le'
word_1.strip('_ ')
'''



Solution

  • You need to replace() in this use case, not strip()

    word.replace('_ ', '')
    

    strip():

    string.strip(s[, chars])

    Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

    replace():

    string.replace(s, old, new[, maxreplace])

    Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

    Strings in Python