"Python" format string and Format function

Source: Internet
Author: User

# # This article is based on Python3, there may be partial content not fit Python2

1. Output of the simplest string:

' popma is so cool ' Print (STR1)

Output:

 is so cool

2. '%s ' formatted string output:

When formatting a string, there is a format character in the string, and the string becomes a template;

For example:

' %s is so cool ' %'popma'print(str2)

The output is the same as above, you can try it.

But if there are multiple format characters, how do you handle them? PytHon with a tuple ( tuples, which may not be easy to understand if the Python data structure has not been learned), passes multiple values to the template, corresponding to the format character one by one.

For example:

' %s is%d ' % ('popma', ')print(STR3)

Where '%d ' represents the number, and this is the same as in C.

3. The Format function

3.1. By location Mapping:

Give examples:

' {0} is {1}, and he is a {2}------{0}'. Format ('popma', '  boy')
out:'popma is, he's a boy------popma'

There is another one that does not write 0 and 1:

' {} is ' {}, and he is a {} '. Format (' Popma ', ' I ', ' Boy ') out: ' POPMA is, he's a boy '

3.2. Through a dictionary-like mapping:

' I am {name}, I am {age} '. Format (name='popma', age=20) out:'I am POPMA, I Am+'

"Python" format string and Format function

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.