Python将所有单词替换为

2024-10-01 15:46:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何删除所有以“赛森”开头的词。在

例如:

test = "This is an example of saison1, saison7 and saison58 could be deleted too"
#test = test.replace("saison1", "")
#test = test.replace("saison58", "")

拥有:

^{pr2}$

怎么做?在


Tags: andoftestanisexamplebethis
2条回答

另一种解决方案:

>>> ' '.join([ word for word in test.split() if not word.startswith('saison') ])
'This is an example of and could be deleted too'

可以使用正则表达式:

import re

test = re.sub(r'\bsaison\d*\b', '', test)

这将删除saison后面紧跟着test中0个或多个数字的任何文本。开头和结尾的\b确保只匹配整个单词,而不是只在中间或结尾包含的单词(后面是数字),或者以saison开头但以其他内容结尾的单词。在

演示:

^{pr2}$

相关问题 更多 >

    热门问题