字符串上的 strip(char)

strip(char) on a string

我正在尝试从我的字符串中删除字符“_”(下划线和 space)。第一个代码无法剥离任何东西。

word_1 的代码如我所愿。谁能告诉我如何修改第一个代码以获得输出 'ale'?

word = 'a_ _ le' 

word.strip('_ ')

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


在此用例中您需要 replace(),而不是 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

.strip 从源字符串的开头和结尾删除目标字符串。

你想要.replace.

>>> word = 'a_ _ le'
>>> word = word.replace("_ ", "")
>>> word
'ale'

.strip() 当必须从字符串的开头和结尾删除传递的字符串时使用。它在中间不起作用。为此,.replace() 用作 word.replace('_ ', '')。这输出 ale