【发布时间】:2021-03-18 11:42:03
【问题描述】:
我有一个字符串格式的列名列表,如下所示:
lst = ["plug", "plug+wallet", "wallet-phone"]
我想添加df[] 和" ' ".
我正在使用正则表达式来替换它。但是当列表如下时,我使用的正则表达式可以正常工作:-
lst = [" 'plug'", "'plug'+'wallet'", "'wallet'-'phone'"]
x=[]
for l in lst: x.append(re.sub(r"('[^+\-*\/'\d]+')", r'df[\1]',l))
print(x)
结果为异常
x: [" df['plug']", "df['plug']+df['wallet']", "df['wallet']-df['phone']"]
但是当列表是这样的时候:
lst = ["plug", "plug+wallet", "wallet-phone"]
x=[]
y=[]
for l in lst: x.append(re.sub(r"('[^+\-*\/'\d]+')", r'\1',l))
for f in x: y.append(re.sub(r"('[^+\-*\/'\d]+')", r'df[\1]',f))
print(x)
print(y)
这给出了:
['plug', 'plug+wallet', 'wallet-phone']
['plug', 'plug+wallet', 'wallet-phone']
我哪里错了?我是否遗漏了第一个正则表达式模式中的任何内容或没有正确传递 r'\1'?
异常输出:
x: [" 'plug'", "'plug'+'wallet'", "'wallet'-'phone'"]
y: [" df['plug']", "df['plug']+df['wallet']", "df['wallet']-df['phone']"]
【问题讨论】:
标签: python regex list python-re