我想使用string的strip函数从字符串中剥离'The',仅不应使用replace函数,我能知道为什么三个单引号吗?
zenPython = '''
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
zen=zenPython.strip('The')
print(zen)
我希望输出的开头没有,但不会出现条纹
答案 0 :(得分:1)
您的输入字符串实际上以空格开头。在这种情况下,您可能要考虑在此处使用re.sub
:
zen = re.sub(r'^\s*The\b', zenPython)
这会在输入的开头删除开头的单词The
,可能在前面带有任意数量的空格,也将其删除。
答案 1 :(得分:1)
.strip()
不适合用于您要实现的功能。它碰巧具有正确的结果(针对此特定的字符串),但出于错误的原因。它将删除开头和结尾的所有字符,与提供的集合匹配。这意味着:
"ThehehxxehT".strip("The") == "xx"
要获得更好的解决方案,请使用另一条评论中提到的re.sub
或按长度手动删除它:
def remove_prefix(original, prefix):
if original.startswith(prefix):
return original[len(prefix):]
else:
return original
zen = remove_prefix(zen, "The")
根据您的情况,您还必须删除字符串中的初始换行符(您的字符串以<newline>The
开头)。
三引号用于允许多行字符串。
答案 2 :(得分:0)
您做得对,但由于The
前面有空格,所以它没有像您期望的那样剥离。默认情况下,strip
将删除所有前导和尾随空格。
因此,您可以尝试以这种方式剥离
>>> zenPython.strip().strip('The')
输出:
" Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than right now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!"