【问题标题】:Remove all characters after a specific set of characters [duplicate]删除一组特定字符之后的所有字符[重复]
【发布时间】:2016-08-09 03:46:55
【问题描述】:
s = 'These are the characters, from this point I want to delete everything'

当 Python 看到“来自”时,我想删除之后的所有内容。

【问题讨论】:

  • s.rpartition('from')[0]
  • @sstyvane rpartition 仅删除最后一次出现之后的内容。 s.partition 会更好

标签: python string


【解决方案1】:

您可以使用takewhile 拆分和重新加入字符串以使用单词直到:

s = 'These are the characters, from this point I want to delete everything'

from itertools import takewhile

new_s = " ".join(takewhile(lambda x: x != "from", s.split(" ")))

您也可以在“from”上拆分一次,然后取之前的字符:

s = 'These are the characters, from this point I want to delete everything'

new_s = s.split("from",1 )[0]

但无论是实际单词还是可能不是您想要的子字符串,这都会根据“来自”进行拆分。

如果您想要精确匹配并处理各种不同的可能性,例如在 from 和 preiod、逗号等之间没有空格。您需要使用 word boundary- 的正则表达式:

import  re
new_s = re.split(r"\bfrom\b",s, 1)[0]

【讨论】:

  • 看起来您的代码实际上省略了单词/子字符串。 OP想要包含它“然后我想删除之后的所有内容”。
  • @user161778,如果是这种情况你可以re.split(r"\bfrom\b",s, 1)[0]+ "from",使用索引将匹配子字符串,当你找不到任何匹配项时会出错
【解决方案2】:

我会使用index

def shorten(s, subs):
    i = s.index(subs)
    return s[:i+len(subs)]

用法:

s = 'These are the characters, from this point I want to delete everything'
print(shorten(s, 'from'))

输出:

这些是字符,来自

【讨论】:

    猜你喜欢
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 2016-08-30
    • 1970-01-01
    相关资源
    最近更新 更多