The format function is used to format strings.
Format
I. Syntax
Replace % by {} and:
Ii. Examples
Name = "bigberg" age = 18msg1 = "my name is {}, and my age is {}. ". format (name, age) msg2 = "my name is {0}, and my age is {1 }. ". format (name, age) msg3 = "my name is {_ name}, and my age is {_ age }. ". format (_ name = name, _ age = age) msg4 = "my name is {1}, and my age is {0 }, and my brother's age is {0 }. ". format (age, name) print (msg1) print (msg2) print (msg3) print (msg4) # output my name is bigberg, and my age is 18.my name is bigberg, and my age is 18.my name is bigberg, and my age is 18.my name is bigberg, and my age is 18, and my brother's age is 18.
The format function of a string can accept unlimited parameters and the position is acceptable.Not in order.Multiple times, But 2.6 cannot be blank {}. It will be available after 2.7.
Iii. subscripts to obtain elements
Info = ["bigberg", 18] msg = '{0 [0]}, {0 [1]}'. format (info) print (msg) # output bigberg, 18
Iv. Format qualifier
Syntax {:}
1. Fill and align
Fill and alignment are often used together
^, <,> Are center, left, right, and back with width. : Enter only one character. If this parameter is not specified, it is filled with spaces by default.
Number = 234 print ('{:> 8 }'. format (number) print ('{: *> 8 }'. format (number) # output 234 ***** 234
2. Precision and Type f
Num = 123.23423 print ('{:. 2f}'. format (num) # output 123.23
Where. 2 indicates the precision of the length of 2, and f indicates the float type.
3. hexadecimal
B, d, o, and x represent binary, decimal, octal, and hexadecimal respectively.
Num = 25 print ('{: B }'. format (num) print ('{: d }'. format (num) print ('{: o }'. format (num) print ('{: x }'. format (num) # output 11001253119