簡體   English   中英

Python re.sub在將多個參數傳遞給函數的for循環中不起作用

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

我試圖通過定義一個函數通過一個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))

用這個 :

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM