Python全棧day14(字串格式化)

來源:互聯網
上載者:User

標籤:指定   zha   log   post   開始   print   int   格式化   列印   

一,%字串格式化

 

  1,使用%s 後面一一對應輸入對應的字串,%s可以接受任何參數

print ("I am %s hobby is zhangsan"%‘lishi‘)
print ("I am %s hobby is %s"%(‘lishi‘,‘zhangsan‘))

I am lishi hobby is zhangsan
I am lishi hobby is zhangsan

 

  2,%d只能接受數字

msg = "I am %s my age is %d"%(‘lishi‘,18)print(msg)I am lishi my age is 18

  

  3,浮點數格式化

tp1 = "percent %f" %99.97623print(tp1)percent 99.976230

 

  4,預設保留小數點後六位,指定保留位元列印

tp1 = "percent %.2f" %99.97623print(tp1)percent 99.98

 

  5,如果需要列印%輸入兩個%即可

tp1 = "percent %.2f%%" %99.97623print(tp1)percent 99.98%

  

  6,使用索引值

tp1 = "I am %(name)s %(age)d" %{"name":"zhangsan","age":18}print(tp1)I am zhangsan 18

  

  7,可選 + 靠右對齊 -靠左對齊 (用途少,還可以加顏色)

tp1 = "I am %(name)-30s %(age)d" %{"name":"zhangsan","age":18}print(tp1)I am zhangsan                       18

  

  9,拼接

print(‘1‘,‘2‘,‘3‘,sep=‘:‘)1:2:3

  

二,format字串格式化

  

  前面使用{}後面必須一一對應

tp1 = "I am {},age is {}".format(‘zhangsan‘,18)print(tp1)I am zhangsan,age is 18

  

  {}裡面加入數字,數字取值為0開始的整數,按照索引取值

tp1 = "I am {1},age is {0}".format(‘zhangsan‘,18)print(tp1)I am 18,age is zhangsan

  

  可以不一一對應但是索引值不能超過索引的位元

tp1 = "I am {1},age is {1}".format(‘zhangsan‘,18)print(tp1)I am 18,age is 18

  

  使用字典形式

tp1 = "I am {name},age is {age}".format(name = ‘zhangsan‘,age = 18)print(tp1)I am zhangsan,age is 18

  

  也可以使用**接一個字典

tp1 = "I am {name},age is {age}".format(**{‘name‘:‘zhangsan‘,"age":18})print(tp1)I am zhangsan,age is 18

  

  使用索引

tp1 = "I am {0[0]},age {0[1]},really {0[2]}".format([1,2,3],[11,22,33])print(tp1)I am 1,age 2,really 3

  

  使用:s :d :f的格式

tp1 = "I am {:s},age {:d},money {:f}".format(‘zhangsan‘,18,888888.8)print(tp1)I am zhangsan,age 18,money 888888.800000

  

  使用*加列表傳遞(必須要加*號)

tp1 = "I am {:s},age {:d}".format(*[‘zhansan‘,18])print(tp1)I am zhansan,age 18

  

  數字格式b二進位 o八進位 d十進位 x小寫16進位 X大寫16進位 %轉換成百分百預設保留小數後六位

tp1 = "number: {:b},{:o},{:d},{:x},{:X},{:%}".format(15,15,15,15,15,15.87623)print(tp1)number: 1111,17,15,f,F,1587.623000%

  

 

  

 

Python全棧day14(字串格式化)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.