简体   繁体   English

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

[英]Python re.sub isn't working in a for loop passing multiple arguments to the function

I am trying to change multiple string values within a single string by defining a function that passes arguments to re.sub via a for loop. 我试图通过定义一个函数通过一个for循环将参数传递给re.sub来更改单个字符串中的多个字符串值。

For some reason when I pass the arguments into re.sub, it has no effect on the string, but if I run the exact same syntax outside of the loop with single argument the regex perfroms as expected. 由于某种原因,当我将参数传递给re.sub时,它对字符串没有任何影响,但是如果我在循环外使用单个参数运行完全相同的语法,则regex perfroms符合预期。 Am I missing something here? 我在这里想念什么吗?

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))

Use this : 用这个 :

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.

Yields: 产量:

/Volumes/MyDrive/iTunes/Music.mp3

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

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