如何在 Python 中列表中"any digits + a delimiter"前面添加分隔符 (#)



嗨,我是python的新手。

当前列表:

current_list = ['Good 33912#This ice 989 cream is so sweet1345#That's a very good bar']

我想要:

new_list = ['Good #33912#This ice 989 cream is so sweet#1345#That's a very good bar']

我想在列表中的"一些数字和哈希(#("前面添加一个分隔符(#(。请帮助

您可以使用re.sub来搜索和替换字符串模式(使用反向引用(:

import re
current_list = ["Good 33912#This ice cream is so sweet1345#That's a very good bar"]
new_list = [re.sub(r'(d+#)', r'#1', i) for i in current_list]
print(new_list)

输出:

["Good #33912#This ice cream is so sweet#1345#That's a very good bar"]

以下是Regex101上regex字符串的解释。

相关内容

最新更新