4

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.

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
kuemme01
  • 472
  • 5
  • 19

2 Answers2

8

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?

Community
  • 1
  • 1
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

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
palsch
  • 5,528
  • 4
  • 21
  • 32
fameman
  • 3,451
  • 1
  • 19
  • 31