Python字串格式化,python字串

來源:互聯網
上載者:User

Python字串格式化,python字串

用於字串的拼接,效能更優。

字串格式化有兩種方式:百分比符號方式、format方式。

百分比符號方式比較老,而format方式是比較先進的,企圖替代古老的方式,目前兩者共存。

1、百分比符號方式

格式:%[(name)][flags][width].[precision]typecode

  • (name)    可選,用於選擇指定的key
  • flags        可選,可供選擇的值有:

    +  靠右對齊:正數的加正號,負數的加負號

    -  靠左對齊:正數前沒有負號,負數前加負號

  • width    可選,佔有寬度
  • .precision    可選,小數點後保留的位元
  • typecode     必選

    s,擷取傳入的對象__str__方法的傳回值,並將其格式化到指定位置

    r,擷取傳入對象的__repr__方法的傳回值,並將其格式化到指定位置

    c,整數:將數字轉換成其unicode對應的值,10進位範圍為0 <= i <=1114111

    o,將整數轉換成八進位表示,並將其格式化到指定位置

    x,將整數轉換成16進位,並將其格式化到指定位置

    d,將整數,浮點數轉化為十進位表示,並將其格式化到指定位置

>>> s = 'i am %s,age %d' %('cai',18)>>> print(s)i am cai,age 18>>> s = 'i am %(n1)s,age %(n2)d' %{'n1':'cai','n2':18}>>> print(s)i am cai,age 18>>> s = 'i am %(n1)+10s,age %(n2)d' %{'n1':'cai','n2':18}>>> print(s)i am        cai,age 18>>> s = 'i am %(n1)+10s,age %(n2)10d' %{'n1':'cai','n2':18}>>> print(s)i am        cai,age         18>>> s = "i am %.3f abcd" %1.2>>> print(s)i am 1.200 abcd

  

2、format方式、

 

i1 = "i am {},age {} ,{}".format('cairui',18,'kk')print(i1)    i am cairui,age 18 ,kki1 = "i am {0},age {1} ,{0}".format('cairui',18)print(i1)    i am cairui,age 18 ,cairuii1 = "i am {name},age {age} ,{name}".format(name='cairui',age=18)print(i1)    i am cairui,age 18 ,cairuii1 = "i am {:s},age {:d} ,{:f}".format('cairui',18,6.1)print(i1)    i am cairui,age 18 ,6.100000

  

聯繫我們

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