0

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'
5
  • If you search in your browser for "Python string replace", you'll find references that can explain this much better than we can manage here. Commented Sep 17, 2019 at 21:08
  • I am not using the same replacement string for every replacement. Commented Sep 17, 2019 at 21:09
  • 1
    Understood -- you replace each occurrence in turn. Where are you stuck? You've shown no attempt to solve the problem. Commented Sep 17, 2019 at 21:11
  • Where did somedir go? I mean the expected output does not match your the definition Commented Sep 17, 2019 at 21:15
  • My bad, corrected that. Commented Sep 17, 2019 at 21:30

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.