Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace keywords, marked with {key} inside Strings with the value in dict["key"] [duplicate]

Tags:

python

string

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.

like image 426
kuemme01 Avatar asked Jan 05 '23 16:01

kuemme01


2 Answers

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?

like image 198
Moinuddin Quadri Avatar answered Jan 13 '23 16:01

Moinuddin Quadri


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
like image 27
fameman Avatar answered Jan 13 '23 16:01

fameman