久久青草精品A片狠狠,日韩欧美视频一区二区,亚洲国码AV日韩,国产精品黄在

Python字符串格式化的方法

2017-09-19 17:18:55 10214

本文介紹了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 ,kk

i1 = "i am {0},age {1} ,{0}".format('cairui',18)
 
print(i1)
 
  i am cairui,age 18 ,cairui

i1 = "i am {name},age {age} ,{name}".format(name='cairui',age=18)
 
print(i1)
 
  i am cairui,age 18 ,cairui

i1 = "i am {:s},age {:d} ,{:f}".format('cairui',18,6.1)
 
print(i1)
 
  i am cairui,age 18 ,6.100000


提交成功!非常感謝您的反饋,我們會繼續努力做到更好!

這條文檔是否有幫助解決問題?

非常抱歉未能幫助到您。為了給您提供更好的服務,我們很需要您進一步的反饋信息:

在文檔使用中是否遇到以下問題: