string formatted output

1. Output according to a certain format, use %s as a placeholder, and the incoming parameter is a tuple, refer to the example.
>>> str="%s,%s!"
>>> val=("hello","world")
>>> print str%val
hello,world!

2. Format floating-point numbers: %.3, where 3 is the decimal place. It is clearer to see the example.
>>> strf="%.3f three decimails"
>>> print strf%1.23456
1.235 three decimails
>>> strf="%.4f three decimails"
>>> print strf%1.23456
1.2346 three decimails

3. Key formatting of characters - width, floating point precision, alignment, 0 padding
is generally this format %d.ds (where d is a specific number), the width before "." is d
after "." The number of s generally means that the floating point number has d decimal places
. %0ds is filled with 0, which means that when the length of s is less than d, it is filled with 0.
Import pi
>>> from math import pi
>>> '%10f'%pi
'  3.141593'
>>> '%10.5f'%pi
'   3.14159'
>>> '%010.4f'%pi
'00003.1416'
>>> '%-10.4f'%pi
'3.1416    '
>>> '%+10.4f'%pi
'   +3.1416'
>>> '%10.4f'%pi
'    3.1416'
>>> '%-10.4f'%pi
'3.1416   
'
There is also a method with *, * the value passed in is a number
>>> '%.*s' %(4,"good day")
'good'
>>> '%.*s'%(2,"good day")
'go'

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327041480&siteId=291194637