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('_ ')
'''
3 Answers
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.
.strip removes the target string from the start and end of the source string.
You want .replace.
>>> word = 'a_ _ le'
>>> word = word.replace("_ ", "")
>>> word
'ale'
.strip() is used when the passed string has to be removed from the start and end of string. It does not work in the middle. For this, .replace() is used as word.replace('_ ', ''). This outputs ale