日本三级片在线观看视频_西西大胆午夜人体视频无码_少妇无码一区二区_亚洲天堂超碰_极品少妇被猛的白浆直流_91精品云霸高清中文字幕_草草五月天伊人_久久少妇无码专区_欧美激欧美啪啪5老太_日韩在线在线成人

Python字符串格式化的方法

2017-09-19 17:18:55 8717

本文介紹了Python字符串格式化,主要有兩種方法,分享給大家,具體如下

用于字符串的拼接,性能更優(yōu)。

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

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

1、百分號方式

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

  • (name)    可選,用于選擇指定的key

  • flags        可選,可供選擇的值有:

    • +  右對齊:正數(shù)的加正號,負數(shù)的加負號

    • -  左對齊:正數(shù)前沒有負號,負數(shù)前加負號

  • width    可選,占有寬度

  • .precision    可選,小數(shù)點后保留的位數(shù)

  • typecode     必選

    • s,獲取傳入的對象__str__方法的返回值,并將其格式化到指定位置

    • r,獲取傳入對象的__repr__方法的返回值,并將其格式化到指定位置

    • c,整數(shù):將數(shù)字轉(zhuǎn)換成其unicode對應的值,10進制范圍為0 <= i <=1114111

    • o,將整數(shù)轉(zhuǎn)換成八進制表示,并將其格式化到指定位置

    • x,將整數(shù)轉(zhuǎn)換成16進制,并將其格式化到指定位置

    • d,將整數(shù),浮點數(shù)轉(zhuǎn)化為十進制表示,并將其格式化到指定位置

>>> 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


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

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

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

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