python的format函数如何理解_python format函数的使用
轉(zhuǎn)載自:http://www.cnblogs.com/kaituorensheng/p/5709970.html
python自2.6后,新增了一種格式化字符串函數(shù)str.format(),威力十足,可以替換掉原來(lái)的%
注:以下操作版本是python2.7
映射示例
語(yǔ)法
通過(guò){} 和 : ?替換 %
通過(guò)位置
>>> '{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'
通過(guò)format函數(shù)可以接受不限參數(shù)個(gè)數(shù)、不限順序
通過(guò)關(guān)鍵字
>>> '{name}:{age}'.format(age=4,name='jihite')
'jihite:4'
>>> '{name}:{age}'.format(age=4,name='jihite',locate='Beijing')
'jihite:4'
format括號(hào)內(nèi)用=給變量賦值
通過(guò)對(duì)象屬性
>>> 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'
通過(guò)下標(biāo)
>>> '{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!'
其實(shí)就是通過(guò)位置
格式限定符
通過(guò){} : 符號(hào)
填充和對(duì)齊
^<>分別表示居中、左對(duì)齊、右對(duì)齊,后面帶寬度
>>> '{:>10}'.format('jihite')
' jihite'
>>> '{:<10}'.format('jihite')
'jihite '
>>> '{:^10}'.format('jihite')
' jihite '
精度和類(lèi)型f
精度常和f一起使用
>>> '{:.2f}'.format(3.1415)
'3.14'
>>> '{:.4f}'.format(3.1)
'3.1000'
進(jìn)制轉(zhuǎn)化
>>> '{:b}'.format(10)
'1010'
>>> '{:o}'.format(10)
'12'
>>> '{:d}'.format(10)
'10'
>>> '{:x}'.format(10)
'a'
其中b o d x分別表示二、八、十、十六進(jìn)制
千位分隔符
>>> '{:,}'.format(1000000)
'1,000,000'
>>> '{:,}'.format(100000.23433)
'100,000.23433'
>>> '{:,}'.format('abcedef')
Traceback (most recent call last):
File "", line 1, in
ValueError: Cannot specify ',' with 's'.
尤其是其中的精度與類(lèi)型,用起來(lái)很方便
總結(jié)
以上是生活随笔為你收集整理的python的format函数如何理解_python format函数的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java上传csv文件上传_java处理
- 下一篇: pythonmysqldb_python