如何删除包含python中某些字符的完整单词

2024-06-28 19:40:18 发布

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

我想删除一个句子中的单词,如果这个单词开始或包含某些字符

例:

string_s = '( active parts ) acetylene cas89343-06-6'

若单词包含cas或以cas开头,则从字符串中删除整个单词

input1 =  '( active parts ) acetylene cas89343-06-6'
output1 = '( active parts ) acetylene'

input2 = '( active parts ) acetylene th.cas1345'
output2 = '( active parts ) acetylene'

Tags: 字符串string字符单词句子activepartscas
3条回答

一艘班轮:

' '.join([*filter(lambda x: "cas" not in x, input1.split())])

re.sub与模式\b[\w-]*cas[\w-]*\b一起使用,并替换为单个空格,然后修剪输出:

string_s = '( active parts ) acetylene cas89343-06-6'
output = re.sub(r'\b[\w-]*cas[\w-]*\b', ' ', string_s).strip()
print(string_s + '\n' + output)

这张照片是:

( active parts ) acetylene cas89343-06-6
( active parts ) acetylene

您可以通过以下方式完成此操作:-

string = "hello how are you"
character = "a"
newString = []
for i in string.split(' '):
    if not character in i:
        newstring.append(i)
newString = ' '.join(newString)

相关问题 更多 >