1. 程式人生 > >Python學習day05-字串格式化、format字串格式化、函式(上)

Python學習day05-字串格式化、format字串格式化、函式(上)

一、字串格式化

①佔位符: %s:萬能的,可以列印所有資料型別,一般用於字串 %d:列印整型 %f:列印浮點數,預設最多列印小數點後6位 ②格式化輸出: (1)普通輸出

msg='i am %s my age is %d' % ('Hello',18)
print(msg)	#i am Hello my age is 18

(2)浮點數輸出 %.3f:保留小數點後3位,此處為保留小數點後3位

tpl = "i am %.3f" % 9.45874
print(tpl)	#9.458

輸出百分比: %f後加兩個%號

tpl = 'percent %.2f %%' % 99.9762
print(tpl)	#percent 99.98 %

(3)字串擷取 %.2s:此處為只打印2個字元

tpl = "i am %.2s" % "HelloWorld"
print(tpl)	#i am He

(4)字典的列印: 括號內填對應的key值

tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18}
print(tpl)	#i am alex age 18

(5)對齊輸出 +:右對齊 -:左對齊

msg='i am %+5s my age %d' %("董雨生",18)
print(msg)	#i am   董雨生 my age 18

③附加:sep 字串的拼接

print('root','x','0','0',sep=':')	#root:x:0:0

二、format格式化輸出

①普通格式輸出 (1)通過花括號一一對應 前面的花括號數量不能多於後面括號內的元素,否則會出錯 預設一一對應

tpl = "i am {}, age {}, adress {}".format("seven",18,"alex")
print(tpl)	#i am seven, age 18, adress alex
tpl = "i am {:s}, age {:d}".format('seven',18)	#帶有佔位符的輸出

(2)通過索引輸出 通過索引輸出,索引不能越界,並且同一索引下的值可以重複被使用

tpl = "i am {2}, age {0}, adress {1}".format("seven",18,"alex")
print(tpl)	#i am alex, age seven, adress 18	

②字典的輸出 (1)字典前加兩個*號 通通過key值列印,並且前面同一key值可以在前面多次使用

tpl = "i am {name}, age {age}".format(**{"name": "seven", "age": 18})
print(tpl)	#i am seven, age 18

(2)其它樣式

tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)

③列表的輸出 字典前加一個*

tpl = "i am {:s}, age {:d}".format(*["seven", 18])
print(tpl)	#i am seven, age 18

③符號輸出 b:2進位制 o:8進位制 x:16進制中的英文小寫 X:16進制中的英文大寫 %:百分比

tpl = "numbers: {:b},{:o},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15.87623)
print(tpl)
#列印:numbers: 1111,17,f,F, 1587.623000%