Format
First, the grammar
Replace% with {} and:
Ii. examples
Name = "Bigberg" age = 18msg1= "My name was {},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) #输出my name is Bigberg,and my age was 18.my name is Bigberg, And my age are 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 the string can accept an unlimited number of parameters, the position can be out of order , can not be used or multiple times , but 2.6 can not be empty {},2.7 later .
Three, subscript gets the element
info = ["Bigberg", 18]msg= ' {0[0]},{0[1]} '. Format (info) print (msg) #输出bigberg, 18
Four, format qualifiers
The syntax is {:}
1. Fill and align
Fill and use with Chi Chang
^, <, > are centered, left-aligned, right-aligned, followed by width. : The character that is padded later, can only be one character, and does not specify a space padding by default.
Number = 234print (' {: >8} '. Format (number)) print (' {:* >8} '. Format (number)) #输出 234*****234
2. Accuracy and type F
num = 123.23423print (' {:. 2f} '. Format (num)) #输出123.23
Where. 2 represents a precision of 2 length, and F denotes float type
3. Binary
B, D, O, and x indicate binary, decimal, octal, and hexadecimal, respectively
num = 25print (' {: b} '. Format (num)) print (' {:d} '. Format (num)) print (' {: o} '. Format (num)) print (' {: x} '. Format (num)) # Output 11001253119