如何在 Python 中的列表中的 "any digits + a delimiter" 前面添加分隔符 (#)
How to add a delimiter (#) in front of "any digits + a delimiter" in a list in Python
嗨,我是 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']
我想在 "some digits and hash(#)" 前面的列表中的任意位置添加分隔符 (#)。请帮助
您可以使用 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'#', 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 上的explanation of regex string。
嗨,我是 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']
我想在 "some digits and hash(#)" 前面的列表中的任意位置添加分隔符 (#)。请帮助
您可以使用 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'#', 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 上的explanation of regex string。