I want to write a method that takes a string and a dict. The method should scan the string and replace every word that inside {word} with the value of the dic["word"].
Example:
s = "Hello my name is {name} and I like {thing}"
dic = {"name": "Mike", "thing": "Plains"}
def rep(s, dic):
return "Hello my name is Mike and I like Plains"
I mean its a simple problem, easy to solve, but I search for the nice python way.
You may unpack the dict
within the str.format
function as:
>>> s = "Hello my name is {name} and I like {thing}"
>>> dic = {"name": "Mike", "thing": "Plains"}
# v unpack the `dic` dict
>>> s.format(**dic)
'Hello my name is Mike and I like Plains'
To know how unpacking works in Python, check: What does ** (double star) and * (star) do for parameters?
Moinuddin Quadri's solution is effective and short. But in some cases you may want to use other patterns surrounding your keywords (e.g. {hello}
instead of ^hello^
). Then you can use a function like this:
def format(string_input, dic, prefix="{", suffix="}"):
for key in dic:
string_input = string_input.replace(prefix + key + suffix, dic[key])
return string_input
This way you can use any surrounding characters you like.
Example:
print(format("Hello, {name}", {"name": "Mike"}))
Hello, Mike
print(format("Hello, xXnameXx", {"name":"Mike"}, "xX", "Xx"))
Hello, Mike
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