python print format用法速查
阿新 • • 發佈:2018-12-05
a= 1
b = 2
a = a + b
b = a - b
a = a - b
print ('a = {0}, b = {1}'.format(a,b))
print ("a={1} b={0} {1}".format("hello", "world"))
a = a ^ b
b = a ^ b
a = a ^ b
print 'a=%d' %a +',b=%d' %b
print 'Price of eggs: $%d' % 42
輸出
a = 2, b = 1
a=world b=hello world
a=1,b=2
Price of eggs: $42
上述植入了兩種交換a和b值的例子,^是按位異或。
if i % 30 == 0:
print("image:", '%04d' % (i+1),\
"cost=", "{:.9f}".format(loss))
('image:', '0001', 'cost=', '3.899574518')
('image:', '0031', 'cost=', '2.469503164')
('image:', '0061', 'cost=', '1.211874366')
('image:', '0091', 'cost=', '0.633342564')
('image:', '0121', 'cost=', '0.465918243')
以上只是程式碼段。.9f 的意思是:dot後面是精度,如
>>>from math import pi
>>>"Pi with three decimals: %.3f"% pi
Pi with three decimals: 3.142
dot前是指定位寬,指的是整個數的位寬(包括小數位),這樣做的目的之一是前面補0。
>>>'%04d'% pi
'0003'