简体   繁体   中英

Replace placeholders in string with replacements sequence

I have a location string with placeholders, used as '#'. Another string which are replacements for the placeholders. I want to replace them sequentially, (like format specifiers). What is the way to do it in Python?

location = '/tmp/#/dir1/#/some_dirx/dir/var/2/#/dir3'
replacements = 'xyz'

result = '/tmp/x/dir1/y/some_dirx/dir/var/2/z/dir3'

You should use the replace method of a string as follows:

for replacement in replacements:
    location = location.replace('#', replacement, 1)

It is important you use the third argument, count , in order to replace that placeholder just once. Otherwise, it will replace every time you find your placeholder.

If your location string does not contains format specifiers ( {} ) you could do:

location = '/tmp/#/dir1/#/some_dirx/dir/var/2/#/dir3'
replacements='xyz'
print(location.replace("#", "{}").format(*replacements))

Output

/tmp/x/dir1/y/some_dirx/dir/var/2/z/dir3

As an alternative you could use the fact that repl in re.sub can be a function:

import re
from itertools import count

location = '/tmp/#/dir1/#/some_dirx/dir/var/2/#/dir3'


def repl(match, replacements='xyz', index=count()):
    return replacements[next(index)]


print(re.sub('#', repl, location))

Output

/tmp/x/dir1/y/some_dirx/dir/var/2/z/dir3

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