Imagine a script that receives a string:
http://whatever.org/?title=@Title@¬e=@Note@
...and a list of tokens:
['arg:Title=SampleTitle', 'arg:Note=SampleNote']
What is the most Pythonic way to interpolate those tokens into the string, such that, using the above example, the following is produced:
http://whatever.org/?title=SampleTitle¬e=SampleNote
I've considered:
Loop through the list and, for every string it contains, split out the token name, and do a regex replace on every instance of @TOKEN_NAME
found; and
Use some sort of templating mechanism (similar to what one can do with Ruby's ERB.template
).
replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.
If order is significant, instead of the dict above you can use an array: b = [ ['i', 'Z'], ['s', 'Y'] ]; for x,y in (b): a = a. replace(x, y) Then if you're careful to order your array pairs you can ensure you don't replace() recursively. It seems that dicts now maintain order, from Python 3.7. 0.
To replace a string in Python, the regex sub() method is used. It is a built-in Python method in re module that returns replaced string. Don't forget to import the re module. This method searches the pattern in the string and then replace it with a new given expression.
To use the Pythonic solution, adopt the str.format
specifications for format string syntax:
>>> template = "http://whatever.org/?title={Title}¬e={Note}"
>>> template.format(Title="SampleTitle", Note="SampleNote")
'http://whatever.org/?title=SampleTitle¬e=SampleNote'
You can also unpack a dictionary of named arguments:
>>> template.format(**{"Title": "SampleTitle", "Note": "SampleNote"})
'http://whatever.org/?title=SampleTitle¬e=SampleNote'
If you're stuck with your input format, you could easily switch to something more useful with a regular expression:
>>> import re
>>> s = "http://whatever.org/?title=@Title@¬e=@Note@"
>>> re.sub(r"@(\w+?)@", r"{\1}", s)
'http://whatever.org/?title={Title}¬e={Note}'
(see regex explanation here)
and process the tokens into a dictionary, too:
>>> tokens = ['arg:Title=SampleTitle', 'arg:Note=SampleNote']
>>> dict(s[4:].split("=") for s in tokens)
{'Note': 'SampleNote', 'Title': 'SampleTitle'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With