標籤:
本節學習Python的格式化輸出,檔案操作以及json的簡單用法
1.格式化輸出
將非字串類型轉換成字串,可以使用函數:str() 或者repr() ,(這兩個函數的區別目前我還沒搞懂,求解答)
>>> str([1,2,3,4])‘[1, 2, 3, 4]‘>>> repr([1,2,3,4])‘[1, 2, 3, 4]‘>>> str(10)‘10‘>>> repr(10)‘10‘
可以使用str.ljust() 、str.rjust()、str.center()來設定字串的對齊
>>> for x in range(1,11): print str(x).ljust(2),str(x*x).ljust(3),str(x*x*x).ljust(4) 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000
我們也可以使用str.format()來設定字串的對齊({}中填充^、<、>分別代表置中、靠左對齊、靠右對齊):
>>> for x in range(1,11): print "{0:<2d} {1:<3d} {2:<4d}".format(x,x*x,x*x*x) 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000
str.format() 的其他使用方法:
>>> print "his name is {},his age is {}".format(‘Jack‘,30)
his name is Jack,his age is 30
>>> print "his name is {1},his age is {0}".format(30,‘Jack‘)
his name is Jack,his age is 30
>>> print "his name is {name},his age is {age}".format(age=30,name=‘Jack‘)
his name is Jack,his age is 30
>>> print "pi is {0:.2f}".format(3.1415926)
pi is 3.14
>>> t={‘name‘:‘Jack‘,‘age‘:30}
>>> print "his name is {0[name]:s},his age is {0[age]:d}".format(t)
his name is Jack,his age is 30
>>> print "his name is {name:s},his age is {age:d}".format(**t)
his name is Jack,his age is 30
我們還有一種格式話輸出的形式,如下所示:
>>> print "pi is %.2f" %(3.1415926)pi is 3.14
Python學習筆記 (第11課)