Python - 替换所有以开头的单词 [英] Python - replace all words start with

查看:58
本文介绍了Python - 替换所有以开头的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何删除所有以saison"开头的单词.

例如:

test = "这是 saison1、saison7 和 saison58 的例子也可以删除"#test = test.replace("saison1", "")#test = test.replace("saison58", "")

要有:

test = "这是一个例子,也可以删除"

如何做到这一点?

解决方案

您可以使用正则表达式:

导入重新test = re.sub(r'\bsaison\d*\b', '', test)

这会从 test 中删除任何出现的文本 saison 后跟 0 个或多个数字.开头和结尾的 \b 确保您只匹配整个单词,而不是恰好只匹配 contain saison 的单词(后跟数字)在中间或结尾,或以 saison 开头但以其他内容结尾.

演示:

<预><代码>>>>进口重新>>>test = "这是一个 saison1、saison7 和 saison58 的例子也可以删除">>>re.sub(r'\bsaison\d*\b', '', 测试)'这是一个例子,也可以删除'

I would like to know how to delete all the words starts with "saison".

For exemple:

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

To have:

test = "This is an example of ,  and  could be deleted too"

How to do this ?

解决方案

You can use a regular expression:

import re

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

This removes any occurrence of the text saison followed by 0 or more digits from test. The \b at the start and end ensures that you only match whole words, not words that happen to only contain saison (followed by digits) in the middle or end, or start with saison but end with something else.

Demo:

>>> import re
>>> test = "This is an example of saison1, saison7 and saison58 could be deleted too"
>>> re.sub(r'\bsaison\d*\b', '', test)
'This is an example of ,  and  could be deleted too'

这篇关于Python - 替换所有以开头的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆