Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing "tokens" in Python string with alternate values

Imagine a script that receives a string:

http://whatever.org/?title=@Title@&note=@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&note=SampleNote

I've considered:

  1. 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

  2. Use some sort of templating mechanism (similar to what one can do with Ruby's ERB.template).

like image 903
ABach Avatar asked Sep 04 '14 14:09

ABach


People also ask

How do you replace a specific part of a string with something else Python?

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.

How do you replace and replace multiple values in Python?

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.

How do you replace a matching string in Python?

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.


1 Answers

To use the Pythonic solution, adopt the str.format specifications for format string syntax:

>>> template = "http://whatever.org/?title={Title}&note={Note}"
>>> template.format(Title="SampleTitle", Note="SampleNote")
'http://whatever.org/?title=SampleTitle&note=SampleNote'

You can also unpack a dictionary of named arguments:

>>> template.format(**{"Title": "SampleTitle", "Note": "SampleNote"})
'http://whatever.org/?title=SampleTitle&note=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@&note=@Note@"
>>> re.sub(r"@(\w+?)@", r"{\1}", s)
'http://whatever.org/?title={Title}&note={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'}
like image 139
jonrsharpe Avatar answered Nov 15 '22 06:11

jonrsharpe