soap
soap

Reputation: 1068

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'

Upvotes: 0

Views: 730

Answers (2)

Dani Mesejo
Dani Mesejo

Reputation: 61910

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

Upvotes: 0

lmiguelvargasf
lmiguelvargasf

Reputation: 69695

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.

Upvotes: 1

Related Questions