Python Beginner
Python Beginner

Reputation: 73

Replace variables programmatically

I have a string like below

str = "http://{ server }:{ port }/images/{ server }/index.html"

The above string could have any number of variables and also one variable could be repeated in the same string as shown in the string.

Additionally, I have an input (dictionary) something like this:

dict = {"server": "xtz", "port": 8080}

How do I programmatically replace the variables with the values from the given dictionary.

I am hoping to write a function to do that.

Upvotes: 0

Views: 681

Answers (2)

user2390182
user2390182

Reputation: 73498

If not for the spaces, you could be really concise using just str.format. Because of them you will need some preprocessing:

s = "http://{ server }:{ port }/images/{ server }/index.html"
d = {"server": "xtz", "port": 8080}

s = s.replace("{ ", "{").replace(" }", "}")

s = s.format(**d)

Upvotes: 1

AKX
AKX

Reputation: 169378

str.format_map() to the rescue!

>>> data = {"server": "xtz", "port": 8080}
>>> template = "http://{server}:{port}/images/{server}/index.html"
>>> template.format_map(data)
'http://xtz:8080/images/xtz/index.html'

Upvotes: 7

Related Questions