Catalog
Formatting of strings
Common format characters
Example :
format() Method
【 example 1】
【 example 2】
Format characters
explain
%s
character string ( use str() Display of )
%r
character string ( use repr() Display of )
%c
Single character
%b
Binary integer
%d
Decimal integer
%i
Decimal integer
%o
Octal integer
%x
Hexadecimal integer
%e
Index ( The base is written as e)
%E
Index ( The base is written as E)
%f、%F、%F
Floating point numbers
%g
Index (e) Or floating point ( According to display length )
%G
Index (E) Or floating point ( According to display length )
%%
character "%""%"
>>> x = 1235
>>> so="%o" % x
>>> so
"2323"
>>> sh = "%x" % x
>>> sh
"4d3"
>>> se = "%e" % x
>>> se
"1.235000e+03"
>>> chr(ord("3")+1)
"4"
>>> "%s"%65
"65"
>>> "%s"%65333
"65333"
>>> "%d"%"555" # Trying to convert a string to an integer for output , Throw an exception
TypeError: %d format: a number is required, not str
>>> int('555') # have access to int() Function to convert a valid numeric string to an integer
555
>>> '%s'%[1, 2, 3]
'[1, 2, 3]'
>>> str((1,2,3)) # have access to str() Function to convert any type of data to a string
'(1, 2, 3)'
>>> str([1,2,3])
'[1, 2, 3]'
More flexible , Not only can you format with position , It also supports formatting with position independent parameter names , And support sequence unpacking format string
print("The number {0:,} in hex is: {0:#x}, the number {1} in oct is {1:#o}".format(5555,55))
Output :
The number 5,555 in hex is:0x15b3, the number 55 in oct is 0o67
analysis :
{0:} perhaps {0} representative format(a0,a1,a2) Medium a0,{0:# Format characters } to a0 format
print("my name is {name}, my age is {age}, and my QQ is {qq}".format(name = "Dong Fuguo",age = 37,qq = "306467355"))
Output :
my name is Dong Fuguo, my age is 37, and my QQ is 306467355