1.%操作符
%操作可以實(shí)現(xiàn)字符串格式化
>>>print("%o" % 10)
12
>>>print("%d" % 10)
10
>>>print("%f" % 10)
10.000000
浮點(diǎn)數(shù)輸出
>>>print("%f" % 3.1415926)?
3.141593 ? ? ?#?%f默認(rèn)保留小數(shù)點(diǎn)后面6為有效數(shù)字
>>>print("%.2f" % 10) ? ? ?#?%.2f保留2位小數(shù)
10.00
>>>print("%.2f" % 3.1415926) ? ? ?#?%.2f保留2位小數(shù)
3.14
'''
#同時(shí)也可以靈活的利用內(nèi)置函數(shù)round(),其函數(shù)形式為:
round(number, ndigits)
number:為一個(gè)數(shù)字表達(dá)式
ndigits:表示從小數(shù)點(diǎn)到最后四舍五入的位數(shù),默認(rèn)數(shù)值為0;
'''
>>>print(round(3.1415926,2)) ?
3.14
2.format 格式化字符串
format 是Python 2.6版本中新增的一個(gè)格式化字符串的方法帅霜,相對(duì)于老版的%格式方法绿贞,它有很多優(yōu)點(diǎn),也是官方推薦使用的方式鲤妥,%方式會(huì)被后面的版本淘汰。該函數(shù)把字符串當(dāng)成一個(gè)模板,通過傳入的參數(shù)進(jìn)行格式化王财,并且使用大括號(hào){}作為特殊字符待提%。
1)通過位置來(lái)填充
通過位置來(lái)填充裕便,format會(huì)把參數(shù)按位置順序來(lái)填充到字符串中绒净,第一個(gè)參數(shù)是0,然后是1不帶編號(hào)偿衰,即{}挂疆,通過默認(rèn)位置來(lái)填充字符串
>>>print('{} {}'.format('hello', 'world'))
hello world
>>>print('{0} {0} {1}'.format('hello', 'world'))
hello hello world ? ? ?#同一個(gè)參數(shù)可以填充多次,這是比%先進(jìn)的地方
2)通過索引
str = 'hello'
list = ['hello',?'world']
tuple = ('hello',?'world')
>>>print("{0[1]}".format(str)) ? ?#0代表第一個(gè)參數(shù)str
e
>>>print("{0[0]}, {0[1]}".format(list) ? ?#0代表第一個(gè)參數(shù)list
hello, world
>>>print("{0[0]}, {0[1]}".format(tuple)
hello, world
>>>print("{p[1]}".format(p=str))
e
>>>print("{p[0]}, {p[1]}".format(p=list))
hello, world
>>>print("{p[0]},{p[1]}".format(p=tuple))
hello, world
3)通過字典的key
在Python中字典的使用頻率非常之高下翎,其經(jīng)常由JSON類型轉(zhuǎn)化得到缤言。同時(shí)隨著人工智能的發(fā)展,越來(lái)越多的數(shù)據(jù)需要字典類型的支持视事,比如MongoDB數(shù)據(jù)的形式就可以看成一種字典類型胆萧,還有推薦算法中的圖算法也經(jīng)常應(yīng)用key-value形式來(lái)描述數(shù)據(jù)。
Tom = {'age': 27, 'gender': 'M'}
>>>print("{0['age']}".format(Tom))
27
>>>print("{p['gender']}".format(p=Tom))
M
4)通過對(duì)象的屬性
format還可以通過對(duì)象的屬性進(jìn)行輸出操作
輸入:
Class Person:
? ? def __init__(self, name, age):
? ? ????self.name = name
? ? ? ? self.age = age
? ? def __str__(self):
? ? ? ? return '{self.name} is {self.age} years old'.format(self=self)
print(Person('Tom', 18)
輸出:
Tom is 18 years old
5)字符串對(duì)齊并且指定對(duì)齊寬度
有時(shí)候我們需要輸出形式符合某些規(guī)則俐东,比如字符串對(duì)齊跌穗,填充常跟對(duì)齊一起使用订晌,符號(hào)^ < >分別是居中、左對(duì)齊蚌吸、右對(duì)齊锈拨,后面帶寬度,冒號(hào)后面帶填充的字符套利,只能是一個(gè)字符推励。如果不指定,則默認(rèn)是用空格填充
>>>print('默認(rèn)輸出: {}, {}'.format('hello', 'world'))
默認(rèn)輸出:?hello, world
>>>print('左右各取10位對(duì)齊: {:10s}, {:>10s}'.format('hello', 'world'))
左右各取10位對(duì)齊:hello ? ? , ? ? ?world
>>>print('取10位中間對(duì)齊: {:^10s}, {:^10s}'.format('hello', 'world'))
取10位中間對(duì)齊: ??hello ? ?, ? world
>>>print('取2位小數(shù): {} is {:.2f}'.format(3.1415926, 3.1415926))
取2位小數(shù): 3.1415926 is 3.14
>>>print('數(shù)值的千分位分割: {} is {:,}'.format(1234567890,?1234567890))
1234567890 is?1,234,567,890
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?整數(shù)規(guī)則表
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?浮點(diǎn)數(shù)規(guī)則表