Python re.sub在将多个参数传递给函数的for循环中不起作用

时间:2018-10-21 20:41:35

标签: python regex

我试图通过定义一个函数通过一个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))

1 个答案:

答案 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