国产欧美日韩第一页|日本一二三不卡视频|在线精品小视频,亚洲第一免费播放区,metcn人体亚洲一区,亚洲精品午夜视频

Python字符串格式化的方法

2017-09-19 17:18:55 5492

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

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

字符串格式化有兩種方式:百分號(hào)方式、format方式。

百分號(hào)方式比較老,而format方式是比較先進(jìn)的,企圖替代古老的方式,目前兩者共存。

1、百分號(hào)方式

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

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

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

    • +  右對(duì)齊:正數(shù)的加正號(hào),負(fù)數(shù)的加負(fù)號(hào)

    • -  左對(duì)齊:正數(shù)前沒(méi)有負(fù)號(hào),負(fù)數(shù)前加負(fù)號(hào)

  • width    可選,占有寬度

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

  • typecode     必選

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

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

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

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

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

    • d,將整數(shù),浮點(diǎn)數(shù)轉(zhuǎn)化為十進(jì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


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

這條文檔是否有幫助解決問(wèn)題?

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

在文檔使用中是否遇到以下問(wèn)題: