简体   繁体   English

使用re.sub并使用Python中的变量将字符串替换为正则表达式

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

Suppose I have a string 假设我有一个字符串

the_string = "the brown fox"

And I wan't to replace the spaces with a number of characters, for example, 5 dash marks 而且我不想用多个字符替换空格,例如5个破折号

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

but this will be a variable, so i cant just do: 但这将是一个变量,所以我不能这样做:

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

I need something like the following: 我需要以下内容:

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

Is something like this possible? 这样的事情可能吗?

Yes, you can do this: 是的,你可以这样做:

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)

You can define a function in re.sub 您可以在re.sub定义一个函数

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

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