python format函數的使用

來源:互聯網
上載者:User

標籤:erro   person   進位   變數賦值   就是   jin   too   call   變數   

轉載自:http://www.cnblogs.com/kaituorensheng/p/5709970.html

python自2.6後,新增了一種格式化字串函數str.format(),威力十足,可以替換掉原來的%

:以下操作版本是python2.7

映射樣本
文法

通過{} 和 :  替換 %

 通過位置
>>> ‘{0} is {1}‘.format(‘jihite‘, ‘4 years old‘)‘jihite is 4 years old‘>>> ‘{0} is {1} {0}‘.format(‘jihite‘, ‘4 years old‘)‘jihite is 4 years old jihite‘

通過format函數可以接受不限參數個數、不限順序

 通過關鍵字
>>> ‘{name}:{age}‘.format(age=4,name=‘jihite‘)‘jihite:4‘>>> ‘{name}:{age}‘.format(age=4,name=‘jihite‘,locate=‘Beijing‘)‘jihite:4‘

format括弧內用=給變數賦值

 通過對象屬性
>>> class Person:...     def __init__(self, name, age):...         self.name,self.age = name, age...     def __func__(self):...         return "This guy is {self.name}, is {self.age} old".format(self=self)... >>> s =Person(‘jihite‘, 4)>>> s.__func__()‘This guy is jihite, is 4 old‘
 通過下標
>>> ‘{0[0]} is {0[1]} years old!‘.format([‘jihite‘, 4])‘jihite is 4 years old!‘>>> ‘{0} is {1} years old!‘.format(‘jihite‘, 4)‘jihite is 4 years old!‘

其實就是通過位置

格式限定符

通過{} : 符號

 填充和對齊

^<>分別表示置中、靠左對齊、靠右對齊,後面頻寬度

>>> ‘{:>10}‘.format(‘jihite‘)‘    jihite‘>>> ‘{:<10}‘.format(‘jihite‘)‘jihite    ‘>>> ‘{:^10}‘.format(‘jihite‘)‘  jihite  ‘
 精度和類型f

精度常和f一起使用

>>> ‘{:.2f}‘.format(3.1415)‘3.14‘>>> ‘{:.4f}‘.format(3.1)‘3.1000‘
 進位轉化
>>> ‘{:b}‘.format(10)‘1010‘>>> ‘{:o}‘.format(10)‘12‘>>> ‘{:d}‘.format(10)‘10‘>>> ‘{:x}‘.format(10)‘a‘

其中b o d x分別表示二、八、十、十六進位

 千位分隔字元
>>> ‘{:,}‘.format(1000000)‘1,000,000‘

  >>> ‘{:,}‘.format(100000.23433)
  ‘100,000.23433‘

>>> ‘{:,}‘.format(‘abcedef‘)Traceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: Cannot specify ‘,‘ with ‘s‘.



尤其是其中的精度與類型,用起來很方便

python format函數的使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.