effect : Print string or numeric value
grammar :print( Variable 1[, Variable 2[, Variable 3[,...]]], seq= Specify the separator , end= Terminator )
There are two common ways :
print(" Formatted string "%( parameter list ))
for example :
name = " Zhang San " age = 14 print("%s Age is %d"%(name, age))
Use format() Format in
for example :
name = " Zhang San " age = 14 print("{} Age is {}".format(name, age))
{} Can be called " Slot ", It is equivalent to a placeholder .format Method will fill the slot of the format string with parameters . If you do not specify the number of parameters to fill the slot , The default is to match from left to right format Variables in the parameter list .
- “ Slot ” Specify the case of filling parameters :
name = " Zhang San " age = 14 print("{0} Age is {1}".format(name, age)) print("{1} Age is {0}".format(name, age))
The result is : Zhang San's age is 14 14 Age is Zhangsan
format Method , The number of the first parameter is 0, The following parameter numbers are incremented by one .
- format() Further use of method formatting
Grammar format :
{< Parameter number >:< Format control flag >}
Example :
print("{0:=^20} Age is {1:*>10}".format(name, age))
result :
========= Zhang San ========= Age is ********14
explain :
There are six types of format control tags , Divide the six into two groups to remember : The first group : fill , alignment , Width ; The second group :<,>,<. precision >,< type >
.
fill : A character used to fill in white space . such as , Specify the character as "=“, The output width is controlled to 5, Output string "123”, The alignment is right , So the output is :
==123
. If you do not specify this character , Then the blank character is filled by default .alignment : Specify the alignment of the output object .
^
Align center ,<
Align left ,>
Right alignment .Width : Specifies the width occupied by the output object . If the required width of the output object itself is less than the specified width , Then according to its alignment , Fill the blank character with the specified fill character .
<,>: Render the output number as its thousandth separator .
print("{:,}".format(100000000))
result :
100,000,000
<. precision >: Specify the precision of the output value , Or string length
Example :
print("{:.2f}".format(20.123456))
result :
20.12
- < type >: Specify the output type
Example :
print("{0:d}\t{0:.2f}".format(1000))
result :
1000 1000.00
When specifying a format control tag in a slot , Follow as much as possible
fill , alignment , Width ,<,>,<. precision >,< type >
The order of . Otherwise, an error will be reported .
Python format Format function | Novice tutorial (runoob.com)
Python Language programming (MOOC) Song Tian