The format() method of python string formatting

Table of contents

String formatting

 common formatting characters

example:

 format() method

【 Example 1】

[Example 2]

String formatting

 common formatting characters

format character

illustrate

%s

string (display using str())

%r

string (display using repr())

%c

single character

%b

binary integer

%d

decimal integer

%i

decimal integer

%o

octal integer

%x

hexadecimal integer

%e

Exponent (base written as e)

%E

exponent (base written as E)

%f、%F、%F

floating point number

%g

exponent (e) or float (depending on display length)

%G

exponent (E) or float (depending on display length)

%%

character"%""%"

example:

>>> 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"		#试图将字符串转换为整数进行输出,抛出异常
TypeError: %d format: a number is required, not str
>>> int('555')		#可以使用int()函数将合法的数字字符串转换为整数
555
>>> '%s'%[1, 2, 3]
'[1, 2, 3]'
>>> str((1,2,3))	#可以使用str()函数将任意类型数据转换为字符串
'(1, 2, 3)'
>>> str([1,2,3])
'[1, 2, 3]'

 format() method

More flexible, not only can use the position for formatting, but also support the use of position-independent parameter names for formatting, and support sequence unpacking format strings

【 Example 1】

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 

Parse:

{0:} or {0} represents a0 in format(a0,a1,a2), {0:#format character} means a0 is formatted 

[Example 2]

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

Guess you like

Origin blog.csdn.net/m0_52177571/article/details/125344658