簡體   English   中英

使用re.sub並使用Python中的變量將字符串替換為正則表達式

[英]Using re.sub and replacing string WITH a regular expression using variables in Python

假設我有一個字符串

the_string = "the brown fox"

而且我不想用多個字符替換空格,例如5個破折號

new_string = "the-----brown-----fox"

但這將是一個變量,所以我不能這樣做:

the_string = 'the brown fox'
new_string = re.sub(r'\s', '-----', the_string)

我需要以下內容:

the_string = 'the brown fox'
num_dashes = 5
new_string = re.sub(r'\s', r'-{num_dashes}', the_string)

這樣的事情可能嗎?

是的,你可以這樣做:

the_string = 'the brown fox'
num_dashes = 5
re.sub(r'\s', '-'*num_dashes, the_string)
def repl(matchobj):
    if matchobj.group():
        #do something
        #return whatever you want to replace

my_str = "the brown fox"

pattern = r"\s+"
print re.sub(pattern, repl, my_str)

您可以在re.sub定義一個函數

暫無
暫無

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

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