How to replace keywords marked with {key} inside lines with a value in dict ["key"]

I want to write a method that takes a string and a dict. The method should scan the string and replace every word inside {word} with the value 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 simple task that is easy to solve, but I'm looking for a good python way.

+4
source share
2 answers

You can unpack dictin str.formathow:

>>> 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 find out how Python work is unpacked, check: What does ** (double star) and * (star) do for parameters?

+8
source

Moinuddin Quadri . , (, {hello} ^hello^). ​​:

def format(string_input, dic, prefix="{", suffix="}"):
    for key in dic:
        string_input = string_input.replace(prefix + key + suffix, dic[key])
    return string_input

, .

:

print(format("Hello, {name}", {"name": "Mike"}))
Hello, Mike
print(format("Hello, xXnameXx", {"name":"Mike"}, "xX", "Xx"))
Hello, Mike
+1

Source: https://habr.com/ru/post/1667471/


All Articles