An example of implementing substrings in a string replacement in Python
- 2021-01-14 06:03:05
- OfStack
Suppose there is a task: given a string, replace the variable in the given character by querying the dictionary. If you use the usual method:
>>> "This is a %(var)s" % {"var":"dog"}
'This is a dog'
>>>
The string.Template class can be used to make the above substitution
>>> from string import Template
>>> words = Template("This is $var")
>>> print(words.substitute({"var": "dog"})) # Passing parameters through a dictionary
This is dog
>>> print(words.substitute(var="dog")) # Passing parameters by keyword mode
This is dog
>>>
When creating an instance of Template, you can use two dollar signs instead of $in the string format, and you can also use ${} to expand variables so that they can be followed by other characters or numbers, much like the languages in Shell or Perl. letter template for example 1:
>>> from string import Template
>>> letter = """Dear $customer,
... I hope you are having a great time!
... If you do not find Room $room to your satisfaction, let us know.
... Please accept this $$5 coupon.
... Sincerely,
... $manager,
... ${name}Inn"""
>>> template = Template(letter)
>>> letter_dict = {"name": "Sleepy", "customer": "Fred Smith", "manager": "Tom Smith", "room": 308}
>>> print(template.substitute(letter_dict))
Dear Fred Smith,
I hope you are having a great time!
If you do not find Room 308 to your satisfaction, let us know.
Please accept this $5 coupon.
Sincerely,
Tom Smith,
SleepyInn
>>>
Sometimes, to prepare a dictionary as an argument to substitute, the simplest way is to set some local variables and pass them to local()(This function creates a dictionary, and key in the dictionary is the local variable, and the value of the local variable is accessed through key).
>>> locals() # When I entered, there were no other variables
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> name = "Alice" # Creating local variables name
>>> age = 18 # Creating local variables age
>>> locals() # To perform locals() The function will see that name, age The key values of the team
{'name': 'Alice', '__builtins__': <module '__builtin__' (built-in)>, 'age': 18, '__package__': None, '__name__': '__mai
__', '__doc__': None}
>>> locals()["name"] # Through the key name To get the value
'Alice'
>>> locals()["age"] # Through the key age To get the value
18
>>>
With the above example in mind, let's look at an example:
>>> from string import Template
>>> msg = Template("The square of $number is $square")
>>> for number in range(10):
... square = number * number
... print msg.substitute(locals())
...
The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The other option is to use the keyword parameter syntax instead of the dictionary and pass the value directly to substitute.
>>> from string import Template
>>> msg = Template("The square of $number is $square")
>>> for i in range(4):
... print msg.substitute(number=i, square=i*i)
...
The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
>>>
You can even pass a dictionary and a keyword at the same time
>>> from string import Template
>>> msg = Template("The square of $number is $square")
>>> for number in range(4):
... print msg.substitute(locals(), square=number*number)
...
The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
>>>
In order to prevent conflicts between the dictionary entry and the value passed by the keyword parameter display, the keyword parameter takes precedence, such as:
>>> from string import Template
>>> msg = Template("It is $adj $msg")
>>> adj = "interesting"
>>> print(msg.substitute(locals(), msg="message"))
It is interesting message