1. 程式人生 > 實用技巧 >Python字串格式化

Python字串格式化

將值轉換為字串並設定格式是拼接字串輸出的重要手段。更靈活方便。join方法拼接只能使用分隔符,且要求被拼接的必須是可迭代物件。由於Python是強型別語言,+拼接字串要求非字串必須先轉換成字串

C語言風格的格式化字串

Python2.5版本之前,拼接字串的解決方案主要使用字串格式設定運算子——百分號。類似於C語言中函式printf。

使用格式:

  1. 佔位符:使用%和格式字元組成,如%s、%d等。s呼叫str()將不是字串的物件轉換為字串。r呼叫repr()。
  2. 修飾符:佔位符中可以使用修飾符,例如:%.3f表示保留3位小數,%03d表示列印3個位置,位數不夠用0補全
  3. format % values,格式字串和被格式的值之間用%分隔
  4. values可以是一個和格式字串佔位符數目相等的元組,或者字典
  5. 預設右對齊,使用 - 號左對齊

使用示例1:

format="hello %s. %s a day!"

values=("world","What")

format % values

執行結果:

'hello world. What a day!'

使用示例2:

import math
format="π is %.5f"
values=(math.pi,)
format % values

執行結果:

'π is 3.14159'

使用示例3:

"%010.3f%% 0x%x,0X%02X" % (99.99999
,10,15)

執行結果

'000100.000% 0xa,0X0F'

使用示例4:

"the num is %-4d" %(20,)

執行結果

'the num is 20  '

Python目前版本的格式化字串

format方法格式化字串語法

"{} {xxx}".format(*args,**kwargs) -> str

其中:

  1. args 是位置引數,是元組
  2. kwargs 是關鍵字引數,是字典
  3. 花括號表示佔位符,按照順序匹配元組中每個位置引數,{n} 表示取位置引數索引為n的值
  4. {xxx} 表示在關鍵字引數中搜索名稱一致的
  5. {{}} 表示列印花括號

位置引數用法

In [85]: "{} {} {}
".format("first","second","third") Out[85]: 'first second third'

關鍵字引數

In [86]: "{name}'s  {age}".format(age=18,name="tom")
Out[86]: "tom's  18"

位置引數和關鍵字引數的混合使用

In [89]: "{foo} {} {bar} {}".format(1,2,foo=3,bar=4)
Out[89]: '3 1 4 2'

可迭代物件元素訪問

In [87]: '{0[0]} {0[1]} or not {0[0]} {0[1]} !'.format(('to','be'))
Out[87]: 'to be or not to be !'

物件屬性訪問

In [88]: from collections import namedtuple
    ...: people=namedtuple('_p',['name','age'])
    ...: p=people(age=18,name="tom")
    ...: "{{{0.name}'s {0.age}}}".format(p)
Out[
88]: "{tom's 18}"

格式化列印中的對齊(預設右對齊)

In [90]: "{} * {} = {}".format(3,2,3*2)
Out[90]: '3 * 2 = 6'

In [91]: "{} * {} = {:>02}".format(3,2,3*2)
Out[91]: '3 * 2 = 06'

In [92]: "{} * {} = {:02}".format(3,2,3*2)
Out[92]: '3 * 2 = 06'

In [93]: "{} * {} = {:<02}".format(3,2,3*2)
Out[93]: '3 * 2 = 60'

居中

In [95]: "{:^10}".format('哈哈')
Out[95]: '    哈哈    '

In [96]: "{:=^10}".format('哈哈')
Out[96]: '====哈哈===='

進位制

In [97]: "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
Out[97]: 'int: 42; hex: 2a; oct: 52; bin: 101010'

In [98]: "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
Out[98]: 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'

In [99]: 'the num is {num:f}'.format(num=10)
Out[99]: 'the num is 10.000000'

In [100]: 'the num is {num:b}'.format(num=10)
Out[100]: 'the num is 1010'

基本轉換總結

字串格式中的型別說明符

型別 含義
b 整數表示為二進位制數
c 將整數解讀為Unicode碼點
d 將整數視為十進位制數,這是整數預設使用的說明符
e 使用科學計數法表示小數(e表示指數)
E 與e相同,但是使用E表示指數
f 將小數表示為定點數
F 與f相同,但對於特殊值(nan和inf)使用大寫表示
g 自動在定點表示法和科學計數法中選擇,預設用於小數的說明符,預設情況下至少有1位小數
G 與g相同,但使用大寫表示指數和特殊值
n 與g相同,但插入隨區域而異的數字分隔符
o 將整數表示為八進位制數
s 保持字串的格式,預設用於字串的說明符
x 將整數表示為十六進位制數並使用小寫字母
X 與x相同,但使用大寫字母
% 將數表示為百分比值