修復 TypeError:沒有足夠的引數導致 Python 中的格式字串錯誤

Manav Narula 2022年5月17日
修復 TypeError:沒有足夠的引數導致 Python 中的格式字串錯誤

在 Python 中,我們可以格式化字串以獲得我們想要的樣式和格式的最終​​結果。

字串格式化還涉及使用帶有% 符號的佔位符值。此方法是一種非常常見的技術,用於在 Python 中為缺失值提供臨時值。

但是,如果不小心,可能會導致 not enough arguments for format string 錯誤,即 TypeError。我們將在本教程中討論此錯誤及其解決方案。

請參閱以下程式碼。

a = 2
b = 4
c = 6
s = "First %s Second %s Third %s" % a, b, c
print(s)

輸出:

TypeError: not enough arguments for format string

我們得到這個錯誤是因為我們在字串中只提供了一個 % 符號來給出值,並且存在三個值。上面的程式碼只考慮第一個值(a)。我們需要在一個元組中傳遞它們來解決這個問題。

例如:

a = 2
b = 4
c = 6
s = "First %s Second %s Third %s" % (a, b, c)
print(s)

輸出:

First 2 Second 4 Third 6

克服此錯誤的另一種方法是使用 format() 函式。 % 方法已過時用於格式化字串。

我們可以在 format() 函式中指定值,並使用花括號 {} 提及缺失值。

請參閱下面的程式碼。

a = 2
b = 4
c = 6
s = "First {0} Second {1} Third {2}".format(a, b, c)
print(s)

輸出:

First 2 Second 4 Third 6

在 Python 3.x 及更高版本中,我們可以使用 fstrings 來提供佔位符字串。此方法是格式化字串的一種更新且更有效的方法。

我們可以像前面的例子一樣在花括號中提供值。

請參閱以下示例。

a = 2
b = 4
c = 6
s = f"First {a} Second {b} Third {c}"
print(s)

輸出:

First 2 Second 4 Third 6
作者: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

相關文章 - Python String