Python字串格式化的方法介紹

巴扎黑
發布: 2017-09-20 09:53:59
原創
1788 人瀏覽過

這篇文章主要介紹了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 = &#39;i am %s,age %d&#39; %(&#39;cai&#39;,18)

>>> print(s)

i am cai,age 18

 

>>> s = &#39;i am %(n1)s,age %(n2)d&#39; %{&#39;n1&#39;:&#39;cai&#39;,&#39;n2&#39;:18}

>>> print(s)

i am cai,age 18

 

>>> s = &#39;i am %(n1)+10s,age %(n2)d&#39; %{&#39;n1&#39;:&#39;cai&#39;,&#39;n2&#39;:18}

>>> print(s)

i am    cai,age 18

 

>>> s = &#39;i am %(n1)+10s,age %(n2)10d&#39; %{&#39;n1&#39;:&#39;cai&#39;,&#39;n2&#39;: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(&#39;cairui&#39;,18,&#39;kk&#39;)
print(i1)
  i am cairui,age 18 ,kk
i1 = "i am {0},age {1} ,{0}".format(&#39;cairui&#39;,18)
print(i1)
  i am cairui,age 18 ,cairui
i1 = "i am {name},age {age} ,{name}".format(name=&#39;cairui&#39;,age=18)
print(i1)
  i am cairui,age 18 ,cairui
i1 = "i am {:s},age {:d} ,{:f}".format(&#39;cairui&#39;,18,6.1)
print(i1)
  i am cairui,age 18 ,6.100000
登入後複製

以上是Python字串格式化的方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!