格式化字符串,就是將字符串以特定格式輸出。
Python2.6 開始,新增了一種格式化字符串的函數 【str.format()】,它增強了字符串格式化的功能。
format函數可以接受不限個參數,位置可以不按順序。
例如:
>>>"{} {}".format("hello", "world") 'hello world'
不設置指定位置,按默認順序
>>> "{1}{2}{0}".format("H","S","5")#設置指定位置 'S5H'
指定的位置,也是以自然數排列的,從0位開始數。
>>> "{1} {0} {1}".format("he", "llo") 'llo he llo'
設置指定位置。包含空格,在{}之間留有空格,所以輸出時也會包含空格。
下面是【str.format()】格式化數字的多種方法:
>>> print("{:.2f}".format(3.1415926)); 3.14
【{:.2f}】輸出保留小數點後兩位
>>>print("{:+.2f}".format(3.14159265)); +3.14 >>>print("{:+.2f}".format(-1)); -1.00
帶符號保留小數點後兩位
>>>print("{:.0f}".format(2.71828)); 3
不帶小數
>>>print("{:0>2d}".format(5)); 05
數字補0(填充左邊,寬度爲2)
>>>print("{:x<4d}".format(5)); 5xxx >>>print("{:x<4d}".format(5)); 10xxx
數字補x(填充右邊,寬度爲4)
>>>print("{:,}".format(100404500)); 100,404,500
**以逗號分隔的數字格式
>>>print("{:.2%}".format(0.12)); 12.00%
百分比格式
>>>print("{:.2e}".format(100000000)); 1.00e+08
**指數記法
>>>print("{:10d}".format(13)); 13#13的前面都是空格,13在寬度爲10的最右邊。
右對齊(默認,寬度爲10)
>>>print("{:<10d}".format(13)); 13 #13的後面都是空格,13在寬度爲10的最左邊。
左對齊(寬度爲10)
>>>print("{:^10d}".format(13)); 13 #13位於寬度爲10的中間。
中間對齊(寬度爲10)
>>>a = print('{:b}'.format(11)); >>>b = print('{:d}'.format(11)); >>>c = print('{:o}'.format(11)); >>>d = print('{:x}'.format(11)); >>>e = print('{:#x}'.format(11)); >>>f = print('{:#X}'.format(11)); >>>a 1011 >>>b 11 >>>c 13 >>>d b >>>e 0xb >>>f 0XB
各個進制
【b】、【d】、【o】、【x】分別是二進制、十進制、八進制、十六進制。
【+】表示在正數前顯示+,負數前顯示-;(空格)表示在正數前加空格
【^】,【<】,【>】分別是居中,左對齊,右對齊,後面帶寬度,【:】號後面帶填充的字符,只能是一個字符,不指定則默認是用空格填充。