Python格式输出汇总
print ('%10s'%('test'))
print ('{:<10}'.format('test'))#left-aligned
print ('{:>10}'.format('test'))#left-aligned
print ('{:10}'.format('test'))# defaut(right-aligned)
print ('{:_<10}'.format('test'))#padding character "_"
print ('{:*<10}'.format('test'))#padding character "*"
print ('{:^10}'.format('test'))#center-aligned
print ('{:^10}'.format('ttest'))#center-aligned if uneven split
# Truncating long strings
print ('{:.5}'.format('xylophone'))
# Combining truncating and padding
print ('{:10.5}'.format('xylophone')) # truncating and padding
# Numbers
print ('{:d}'.format(42))
print ('{:f}'.format(3.14159))
# Padding numbers
print ('{:4d}'.format(42))
print ('{:04d}'.format(42))
print ('{:06.2f}'.format(3.14159))
print ('{:+d}'.format(42))
# Use a space character to indicate that negative numbers should be
# prefixed with a minus symbol and a leading space should be used
# for positive ones
print ('{: d}'.format(42))
print ('{: d}'.format(-42))
print ('{:=5d}'.format(-23))# control the position of the sign symbol
print ('{:=5d}'.format(23))
print ('{:=+5d}'.format(23))
# Named placeholders
data = {'first': 'Hodor', 'last':'Hodor!'}
print ('{first} {last}'.format(**data))
print ('{last} {first}'.format(**data))
print ('{first} {last}'.format(first='Hodor', last='Hodor!'))
person = {'first': 'Jean-Luc', 'last': 'Picard'}
print (person['first']) # person[first] is NOT correct
print ('{p[first]} {p[last]}'.format(p=person)) #p['first'] is NOT correct
data = [10,20,30,40,50,60]
print ('{d[4]} {d[5]}'.format(d=data))
class Plant(object):
type = 'tree'
print ('{p.type}'.format(p=Plant()))
class Plant(object):
type = 'tree'
kinds = [{'name':'oak'}, {'name':'maple'}]
print ('{p.type}: {p.kinds[0][name]}'.format(p=Plant()))
# Datatime
from datetime import datetime as dt
print (dt(2001,2,3,4,5))
print ('{:%Y-%m-%d %H:%M}'.format(dt(2001,2,3,4,5)))
# Parametrized formats
print ('{:{align}{width}}'.format('test', align='^', width='10'))
print ('{:{prec}} = {:.{prec}f}'.format('Gibberish', 2.7182, prec = 3))
print ('{:{width}.{prec}f}'.format(2.7182, width = 5, prec =2))
输出结果:
test
test
test
test
test______
test******
test
ttest
xylop
xylop
42
3.141590
42
0042
003.14
+42
42
-42
- 23
23
+ 23
Hodor Hodor!
Hodor! Hodor
Hodor Hodor!
Jean-Luc
Jean-Luc Picard
50 60
tree
tree: oak
2001-02-03 04:05:00
2001-02-03 04:05
test
Gibberish = 2.718
2.72