在Python 3中删除字符串的一部分

4

我一直在查看re文档、搜索网络和尝试许多方法几个小时,但仍然找不到一种方法来删除字符串的某个部分。

因此,这个字符串看起来是这样的:

Linda Lost (Secret Icecone Incorporated) lost their Kronos in Osmon (The Forge). Final Blow by Liberty Prime (Exit-Strategy) flying in a Arbitrator. Total Value: 1,865,802,910.96 ISK

基本上,当从网站的元数据中提取字符串时,所有名称和内容都会更改。唯一确定的是“Final Blow by”、“Total Value:”和“ISK”的内容是相同的。

因此,我一直在尝试弄清楚的是如何删除整个“Total Value:1,865,802,910.96 ISK”部分,并返回其前面的内容。

非常感谢任何帮助。谢谢!


3
someString[:someString.find('Total Value:')] - poke
1
太棒了!感谢你的帮助。它运行得非常好。 - Cameron
1
s.split('Total Value:')[0] - Iron Fist
re.search(r'.*(?=Total Value:)', s).group() - Iron Fist
3个回答

2

这将起作用。

t = "Linda Lost (Secret Icecone Incorporated) lost their Kronos in Osmon (The Forge). Final Blow by Liberty Prime (Exit-Strategy) flying in a Arbitrator. Total Value: 1,865,802,910.96 ISK"

where = t.rfind(" Total")

print(t[:where])


使用 Total.+ 是危险的,因为 Total 可能会出现在其中一个名称的一部分。更具体的模式或非贪婪重复可能会使其安全地工作。 - Blckknght
你没有看到模式中的 '$' 吗?它意味着所描述的模式必须匹配到结尾。 - Ishaq Khan
问题在于匹配模式的开头。如果字符串开头不是"Linda Lost",而是"Foo Total",那么你提供的匹配模式将遗弃除了"Foo"之外的所有内容。请注意,我可能更占优势,因为我知道所描述的字符串的含义(它是来自MMO游戏Eve Online的Killmail的一部分)。我不会感到惊讶,看到玩家或公司(Eve的公会)故意使用会破坏粗心的Killmail解析代码的名称(如"Total Value"或"Final Blow by")。 - Blckknght
朋友,你是对的。我的代码不够灵活。因此我改了代码,现在更简单了。 - Ishaq Khan

2
您可以使用以下正则表达式:
pat = re.compile(r'(.*?)Total Value: [\d,.]* ISK')
m = pat.match(s)
m.group(1)
'Linda Lost (Secret Icecone Incorporated) lost their Kronos in Osmon (The Forge). Final Blow by Liberty Prime (Exit-Strategy) flying in a Arbitrator. '

或者你可以采用以下方法进行黑客攻击。
s.rsplit('.',2)[0]
'Linda Lost (Secret Icecone Incorporated) lost their Kronos in Osmon (The Forge). Final Blow by Liberty Prime (Exit-Strategy) flying in a Arbitrator'

0

这个有效。

t = "Linda Lost (Secret Icecone Incorporated) lost their Kronos in Osmon (The Forge). Final Blow by Liberty Prime (Exit-Strategy) flying in a Arbitrator. Total Value: 1,865,802,910.96 ISK"

t.split('Total Value:')[0]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接