1

I have a string with some placeholder in it like:

url = "http://www.myserver.com/$abc/$foo_or_bar/$xy"

I cannot use Templates (http://is.gd/AKmGxa), because my placeholder-strings needs to be interpreted by some logic.

I need to iterate over all exisiting placeholders and replace them by a code-generated value.

How can I do this? TIA!

1 Answer 1

1

Using re.sub which can accept replacement function as a second argument;

>>> url = "http://www.myserver.com/$abc/$foo_or_bar/$xy"
>>>
>>> def some_logic(match):
...     s = match.group()  # to get matched string
...     return str(len(s) - 1)  # put any login you want here
...
>>> import re
>>> re.sub('\$\w+', some_logic, url)
'http://www.myserver.com/3/10/2'

BTW, string.Template also can be used if you pass custom mapping:

>>> class CustomMapping:
...     def __getitem__(self, key):
...         return str(len(key))
...
>>> import string
>>> url = "http://www.myserver.com/$abc/$foo_or_bar/$xy"
>>> string.Template(url).substitute(CustomMapping())
'http://www.myserver.com/3/10/2'
Sign up to request clarification or add additional context in comments.

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.