Python string Formatting

Source: Internet
Author: User

1. Use%s to indicate

s ="welcome%s to login%s"%("Alex"," China")Print(s) s="welcome% (name) s to login% (city) s"%{"name":"Alex"," City":"Wuhan"}Print(s)

s = "%10s is%+10d years old"% ("Alex",-10)
Print (s)

Alex is-10 years old
Explanation: The first string accounted for 10 characters, right-aligned, the second also accounted for 10 characters, right-aligned, + number positive front plus +, negative before plus-.

s = "The pi is%.4f"% (3.1415926)
Print (s)
The pi is 3.1416
or the following notation.
s = "The Pi is% (p)." 4f "%{" P ": 3.1415926}
s = "The pi is ====%c=====%x======%o"% (65,15,15)
Print (s)
The pi is ====a=====f======17
s = "Alex percent percent"
Print (s)

S1 = "Alex%s%%%%"% ("SB")
Print (S1)

Output:

Alex is a percent.
Alex SB. Percent #一旦前面出现过% placeholder, followed by a percent only

2. Formatting with format

" ----->{0}------>{1}------>{0} ". Format ("Alex")print  (s)----->alex------ >10------>alex

s = "----->{name:s}------>{age:d}------>{name:s}". Format (name= "Alex", age=10)
Print (s)
----->alex------>10------>alex

s = "-----{: 9^20s}=====". Format ("Alex")
Print (s)
-----99999999alex99999999=====
Explanation: The string width is 20, centered, and the insufficient part is filled with 9来

S2 = "======{:* <20s}======{:+d}======{: #b}". Format (' Alex ', 123,15)
Print (s2)
======alex****************======+123======0b1111
Explanation: #号只是给b, o,x preceded by 0b,0o,0x symbol

S3 = "{:. 2%}". Format (0.234567)
Print (S3)
23.46%
s = "{} is {} years old". Format ("Alex", 18)
Print (s)

S1 = "{} is {} years old". Format (*["Alex", 18])
Print (S1)

S2 = "{name} is {age} years old". Format (**{"name": "Alex", "Age": 18})
Print (s2)

Python string Formatting

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.