Python學習筆記 (第11課)

來源:互聯網
上載者:User

標籤:

本節學習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課)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.