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