【问题标题】:Why does split() return one extra item? [duplicate]为什么 split() 会返回一个额外的项目? [复制]
【发布时间】:2020-08-01 22:52:26
【问题描述】:
我有这个字符串,我想使用指定的分隔符来分隔它。为什么长度是 4 而不是 3?
brain = " Know yourself! Understand yourself! Correct yourself! "
brain = brain.strip()
change = brain.split("yourself!")
print(len(change))
【问题讨论】:
标签:
python-3.x
string
split
【解决方案1】:
因为您想要与(您自己!)拆分的单词位于字符串的末尾(或开头)。
你可以试试这个解决方案:
def is_not_none(element):
if element is not None:
return element
brain = "know yourself! Understand yourself! Correct yourself! "
brain = brain.strip()
brain = list(filter(is_not_none, brain.rsplit('yourself!')))
print(brain)