简体   繁体   English

如何在Python列表中的“任何数字+分隔符”前面添加分隔符(#)

[英]How to add a delimiter (#) in front of “any digits + a delimiter” in a list in Python

Hi I am new to python. 嗨,我是python新手。

Current List: 当前列表:

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

I want to have: 我希望有:

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

I want to add a delimiter(#) in front of "some digits and hash(#)" wherever found in the list. 我想在列表中的任何位置的“一些数字和哈希(#)”前面添加定界符(#)。 Please help 请帮忙

You can use re.sub for searching and substituting string patterns (using back reference): 您可以使用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)

Output: 输出:

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

Here is explanation of regex string on Regex101. 这是Regex101 上正则表达式字符串的说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM