字符串上的strip(字符)

2024-04-30 06:56:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从字符串中去掉字符“u”(下划线和空格)。第一个代码无法删除任何内容

单词_1的代码正是我想要的。有人能告诉我如何修改第一个代码以获得输出“ale”吗

word = 'a_ _ le' 

word.strip('_ ')

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



Tags: 字符串代码le内容字符单词wordstrip
3条回答

在这个用例中,您需要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

相关问题 更多 >