Python programming string Template usage Example Analysis, pythontemplate

Source: Internet
Author: User

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.