Python programming string Template usage Example Analysis, pythontemplate
This document describes how to use a string Template in Python programming. We will share this with you for your reference. The details are as follows:
# Coding = utf8''' string formatting operator. The programmer needs to specify the conversion type parameters, such as whether to convert to a string, an integer, or another type. The advantage of the new string template is that you do not need to remember all the relevant details, but use the dollar sign ($) like in the shell-style scripting language ). since the new string introduces the Template object, the Template object has two methods: substitute () and safe_substitute (). Substitute () is more rigorous. If the key is missing, a KeyError exception is reported. Safe_substitute () directly displays the string without a key. ''' # Import Template object from string import Templatedef stringTemplate (): # create a Template instance tmp = Template ("I have $ {yuan} yuan, I can buy $ {how} hotdog ") yuanList = [1, 5, 8, 10, 12, 13] for yu in yuanList: # substitute () output by string in Template # and assign Substitute = tmp to the corresponding key. substitute (yuan = yu, how = yu) print Substitute print for yu in yuanList: # using the substitute function lacks the key value package KeyError try: lackHow = tmp. substitute (yuan = yu) print lackHo W print failed t KeyError, e: print "substitute lack key", e print for yu in yuanList: # safe_substitute () if the key is missing, # directly display the string intact. Safe_substitute = tmp. safe_substitute (yuan = yu) print safe_substitute print # Call the stringTemplate function stringTemplate ()
Running result: