简体   繁体   中英

How to dynamically parse python string templates?

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!

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'

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