我试图通过定义一个函数通过一个for循环将参数传递给re.sub来更改单个字符串中的多个字符串值。
由于某种原因,当我将参数传递给re.sub时,它对字符串没有任何影响,但是如果我在循环外使用单个参数运行完全相同的语法,则regex perfroms符合预期。我在这里想念东西吗?
import re
#This is my function:
def mult(string, *args):
for arg in args:
result = re.sub(arg, '', string)
return result
path = 'file://Volumes/MyDrive/iTunes/Music.mp3'
print(mult(path, '\'file:/\''))
#produces no change to the string
#This is the normal re.sub which works fine:
print(re.sub('file:/', '', path))
答案 0 :(得分:0)
使用此:
import re
def mult(string, *args):
for arg in args:
result = re.sub(arg, '', string)
return result
path = 'file://Volumes/MyDrive/iTunes/Music.mp3'
print(mult(path, 'file:/'))
#Notice the change to the args. Your string is wrong.
收益:
/Volumes/MyDrive/iTunes/Music.mp3