为什么输出没有条带化 'The'

Why the output is not getting striped of 'The'

我只想使用字符串的剥离函数从字符串中剥离 'The' 不应该使用替换函数,我能知道为什么三个单引号吗?

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)

我希望输出没有开始,但它没有条纹

您做得对,但是由于在 The 之前有前导 space,它不是您预期的 striping。默认情况下,strip 将删除所有前导和尾随 spaces。

所以,你可以这样尝试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!"

您输入的字符串实际上以 space 开头。在这种情况下,您可能需要考虑在此处使用 re.sub

zen = re.sub(r'^\s*The\b', zenPython)

这会删除输入开头的初始单词 The,前面可能有任意数量的白色space,这也将被删除。

.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 开头)。

三重引号允许多行字符串。