欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python字符串格式化的方法(兩種)

 更新時間:2017年09月19日 11:03:57   作者:瀟瀟、寒  
這篇文章主要介紹了Python字符串格式化的方法(兩種) ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

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

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

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

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

1、百分號方式

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

  • (name)    可選,用于選擇指定的key
  • flags        可選,可供選擇的值有:
    • +  右對齊:正數(shù)的加正號,負(fù)數(shù)的加負(fù)號
    • -  左對齊:正數(shù)前沒有負(fù)號,負(fù)數(shù)前加負(fù)號
  • width    可選,占有寬度
  • .precision    可選,小數(shù)點后保留的位數(shù)
  • typecode     必選
    • s,獲取傳入的對象__str__方法的返回值,并將其格式化到指定位置
    • r,獲取傳入對象的__repr__方法的返回值,并將其格式化到指定位置
    • c,整數(shù):將數(shù)字轉(zhuǎn)換成其unicode對應(yīng)的值,10進(jìn)制范圍為0 <= i <=1114111
    • o,將整數(shù)轉(zhuǎn)換成八進(jìn)制表示,并將其格式化到指定位置
    • x,將整數(shù)轉(zhuǎn)換成16進(jìn)制,并將其格式化到指定位置
    • d,將整數(shù),浮點數(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 

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論