如何在 Python 中將資料值插入字串?


我們可以使用各種格式將資料值插入字串。我們可以用它來除錯程式碼、生成報表、表單和其他輸出。在本主題中,我們將瞭解三種字串格式化方法以及如何將資料值插入字串。

Python 有三種格式化字串的方法

  • % - 舊式方法(Python 2 和 3 中都支援)

  • () - 新式方法(Python 2.6 及以上版本)

  • {} - f-字串(Python 3.6 及以上版本)

舊式方法:%

舊式字串格式化的形式為 format_string % data。格式字串不過是插值序列。

語法
描述
%s
字串
%d
十進位制
%x
十六進位制整數
%o
八進位制整數
%f
十進位制浮點數
%e
指數浮點數
%g
十進位制或指數浮點數
%%
字面量 %


# printing integer with % style type.
print('output \nprinting a number in string format %s' % 42)
print('printing a number in string decimal %d' % 42)
print('printing a number in string hexa-int %x' % 42)
print('printing a number in string exponential-float %g' % 42)

輸出

printing a number in string format 42
printing a number in string decimal 42
printing a number in string hexa-int 2a
printing a number in string exponential-float 42

使用舊格式 % 進行字串和整數插值

字串中的 %s 表示插入一個字串。字串中 % 出現的次數需要與 % 後面字串之後的的資料項數量相匹配。

單個數據項緊隨其後的那個最終 %。多個數據必須分組到一個元組中,請參見下面的示例。

您還可以將格式字串中 % 和型別說明符之間的其他值新增到指定最小和最大寬度、對齊方式以及填充字元。

1. + means right-align
2. - means left-align
3. . means separate minwidth and maxchars.
4. minwidth means mimimu field width to use
5. maxchars means how many characters/digits to print from the data value


player = 'Roger Federer'
country = 'Legend'
titles = 20

# note please try this only on Python 2. If you are running on Python3 output for below commands will vary a lot.

print('Output \n*** Tennis player %s From %s had won %d titles ' %(player,country,titles))
print('%s' % player) # print player
print('%5s' % player) # print firstname of player
print('%-7s' % player) # Last Name of player
print('%5.7s' % player) # Last Name of player with 5 leading spaces

輸出

*** Tennis player Roger Federer From Legend had won 20 titles
Roger Federer
Roger Federer
Roger Federer
Roger F

使用新式方法:{} 進行字串和整數插值

如果您使用的是 Python 3.5 或更高版本,則可以使用下面部分中描述的“新式”格式化。

“{}” 格式化的語法為 format_string.format(data)。

請記住,format() 函式的引數需要按照格式字串中 {} 佔位符的順序排列。有時為了提高可讀性,您可以將字典或命名引數傳遞給 format。

player = 'Roger Federer'
player = 'Roger_Federer'
country = 'Legend'
titles = 20

print('Output \n{}'.format(player))
print(' *** Tennis player {} From {} had won {} titles '.format(player,country,titles))

# positonal arguments
print(' *** Tennis player {1} From {2} had won {0} titles '.format(titles,player,country))

# named arguments
print(' *** Tennis player {player} From {country} had won {titles} titles '.format(player = 'Roger Federer',country = 'Legend',titles = 20))

# Dictionary arguments
print(' *** Tennis player {player} From {country} had won {titles} titles '.format(player = 'Roger Federer',country = 'Legend',titles = 20))

# alignment left '<' (default)
print(' *** Tennis player {} From {:<5s} had won {:<5d} titles '.format(player,country,titles))

# alignment left '<' (default)
print(' *** Tennis player {} From {:<5s} had won {:<5d} titles '.format(player,country,titles))

# alignment center '^'
print(' *** Tennis player {} From {:^10s} had won {:^10d} titles '.format(player,country,titles))

# alignment right '>'
print(' *** Tennis player {} From {:>10s} had won {:>10d} titles '.format(player,country,titles))


輸出

Roger_Federer
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger Federer From Legend had won 20 titles
*** Tennis player Roger Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles

使用最新式方法:f-字串 進行字串和整數插值

f-字串出現在 Python 3.6 中,並很快成為推薦的字串格式化方式。我個人使用這種格式。要建立 f-字串

1. 在起始/初始引號之前使用字母 f/F。
2. 在花括號 ({}) 內包含變數名或表示式以將其值插入字串。

player = 'Roger_Federer'
country = 'Legend'
titles = 20

print(f"Output \n *** Tennis player {player} From {country} had won {titles} titles ")
print(f" *** I hope {player} wins another {titles - 10} titles ")
print(f" {'*' * 3} Tennis player {player.upper()} From {country:.^10} had won {titles} titles")

輸出

*** Tennis player Roger_Federer From Legend had won 20 titles
*** I hope Roger_Federer wins another 10 titles
*** Tennis player ROGER_FEDERER From ..Legend.. had won 20 titles

現在我們已經介紹了基礎知識,讓我們進入一些實際問題,以及我為什麼建議開始使用格式化字串。

titles = [
('federer', 20),
('nadal', 20),
('djokovic', 17),
]
print('Output\n')
for i, (player, titles) in enumerate(titles):
print('#%d: %-10s = %d' % (
i + 1,
player.title(),
round(titles)))

輸出

#0: federer = 20
#1: nadal = 20
#2: djokovic = 17

顯然,在向高層傳送報告時,不希望看到從 0 開始的索引,他們希望從 1 開始。羅傑·費德勒作為網球傳奇人物,我個人希望將他表示為 #1 而不是 #0。

現在要進行更改,請檢視在使用舊格式時程式碼的可讀性是如何變化的。

titles = [
('federer', 20),
('nadal', 20),
('djokovic', 17),
]
print('Output\n')
for i, (player, titles) in enumerate(titles):
print('#%d: %-10s = %d' % (
i + 1,
player.title(),
round(titles)))

輸出

#1: Federer = 20
#2: Nadal = 20
#3: Djokovic = 17

總之,我提供了一個示例來說明為什麼 f-字串更容易管理。

old_school_formatting = (
' Tennis Legeng is %(player)s, '
' %(player)s had won %(titles)s titles, '
'and he is from the country %(country)s.')
old_formatted = old_school_formatting % {
'player': 'Roger Federer',
'titles': 20,
'country': 'Swiss',
}
print('Output\n' + old_formatted)

輸出

Tennis Legeng is Roger Federer, Roger Federer had won 20 titles, and he is from the country Swiss.


new_formatting = (
' Tennis Legeng is {player}, '
' {player} had won {titles} titles, '
'and he is from the country {country}')
new_formatted = new_formatting.format(
player= 'Roger Federer',
titles= 20,
country= 'Swiss',
)
print('Output\n' + new_formatted)

輸出

Tennis Legeng is Roger Federer, Roger Federer had won 20 titles, and he is from the country Swiss

這種風格稍微不太冗餘,因為它消除了字典中的一些引號以及格式說明符中相當多的字元,但它並不引人注目。

更新於: 2020-11-10

191 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.