删除某些字符后的n个字符

问题描述 投票:0回答:1

我有一个看起来像这样的字符串:

*45hello I'm a string *2jwith some *plweird things

我需要删除所有*和紧跟这些*的2个字符,以获取此信息:

hello I'm a string with some weird things

有没有一种可行的方法可以在不迭代字符串的情况下进行此操作?

谢谢!

python regex string
1个回答
0
投票

使用正则表达式:

import re
s = "*45hello I'm a string *2jwith some *plweird things"
s = re.sub(r'\*..', '', s)

0
投票

您可以使用正则表达式:

import re
regex = r"\*(.{2})"
test_str = "*45hello I'm a string *2jwith some *plweird things"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, '', test_str, 0, re.MULTILINE)
© www.soinside.com 2019 - 2024. All rights reserved.