我想要做的是去掉星号之间的数字,并保持其他数字在附近。我运行我的正则表达式,但它删除了星号之间的所有内容。
import re
msg = """
1 x * Build your pizza * ($ 99MXN)
1 x * Baitz Cinnamon 16 pieces * ($ 44.50 MXN)
1 x * Potatoes 220 g * ($ 44.50 MXN) """
re.sub(r'\*.*\*', "", msg)
我所期望的结果是:
"""
1 x * Build your pizza * ($ 99MXN)
1 x * Baitz Cinnamon pieces * ($ 44.50 MXN)
1 x * Potatoes g * ($ 44.50 MXN)
"""
发布于 2021-11-09 04:04:49
您可以将lambda
传递给re.sub for repl
,并筛选出星号中包含的子字符串的数字:
result = re.sub('\*.+\*',
lambda x: ''.join(c for c in x.group(0) if not c.isdigit()),
msg)
print(result)
1 x * Build your pizza * ($ 99MXN)
1 x * Baitz Cinnamon pieces * ($ 44.50 MXN)
1 x * Potatoes g * ($ 44.50 MXN)
如果不想使用上述方法(不删除前面/后面的空格字符),可以使用嵌套re.sub
:
result = re.sub('\*.+\*',
lambda x: re.sub('\s*\d+\s*','',x.group(0)),
msg)
print(result)
1 x * Build your pizza * ($ 99MXN)
1 x * Baitz Cinnamonpieces * ($ 44.50 MXN)
1 x * Potatoesg * ($ 44.50 MXN)
https://stackoverflow.com/questions/69892662
复制相似问题