2015-08-18 57 views
3

假设我有一个字符串使用应用re.sub和替换字符串使用变量在Python

the_string = "the brown fox" 

我wan't用字符数来替换空间,例如,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) 

是这样的可能吗?

+0

是有一些原因,你不想使用[str.replace(旧的,新\ [,count \])](https://docs.python.org/3/library/stdtypes.html#str.replace)?你可以写'new_string = the_string.replace('',' - '* num_dashes)'。 –

+0

在这种情况下,这将工作得很好。 str.replace是否使用正则表达式?例如,如果我需要替换一个或多个空格。可能是一个,可能是多个。 – Eddie

+0

那么你是正确的。您可能想要使用're'模块来创建可变数量的空白字符。 'str.replace'方法不适用于正则表达式。 –

回答

3

定义函数是的,你可以这样做:

the_string = 'the brown fox' 
num_dashes = 5 
re.sub(r'\s', '-'*num_dashes, the_string) 
0
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