Use of Substitute () in Python template

Source: Internet
Author: User

In Python, the template can be used to fix the formatting of strings and reuse them.

The template belongs to a class in string and can be invoked in the following ways to use his words:

 from string Import Template

We use the following code:

>>> s = Template ('there  ${moneytype} is  ${money}')' Dollar ', money=)

Run results show "there Dollar is 12"

So we can replace the data in it.

But we're going to replace one of those data?

>>> print S.substitute (Moneytype ='Dollar') Traceback (most recent): File"<pyshell#509>", line1,inch<module>Print S.substitute (Moneytype='Dollar') File"C:\Python27\lib\string.py", line172,inchSubstitutereturnself.pattern.sub (Convert, self.template) File"C:\Python27\lib\string.py", line162,inchconvert Val=Mapping[named]keyerror:' Money'

An error has been made. It doesn't look like this.

This is going to use the safe_substitute.

' Dollar ' ) There  is  ${money}

Note: I previously looked at the reference book $ after using the "()" bracket, but I ran an error on the 2.7.9, and then tried it, bold later version does not support "()". There is no problem using "{}" or not writing parentheses.

Use of Substitute () in Python template

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.