简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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