GDScript 格式化字串

Godot 提供多種方式可動態變更字串內容:

  • 格式化字串: var string = "I have %s cats." % "3"

  • The String.format() method: var string = "I have {0} cats.".format([3])

  • 字串串接: var string = "I have " + str(3) + " cats."

本頁將說明如何使用格式化字串,並簡單介紹 format() 方法與字串串接。

格式化字串

格式化字串 是用來重複利用文字樣板,簡潔地產生不同但類似字串的方法。

格式化字串和一般字串類似,只是它們包含像 %s 這樣的預留位置符號。這些預留位置可由傳入的參數取代。

來看看這個實際的 GDScript 範例:

# Define a format string with placeholder '%s'
var format_string = "We're waiting for %s."

# Using the '%' operator, the placeholder is replaced with the desired value
var actual_string = format_string % "Godot"

print(actual_string)
# Output: "We're waiting for Godot."

預留位置總是以 % 開頭,接下來的字元稱為 格式規範,決定該值如何被轉換為字串。

上方範例中的 %s 是最簡單的預留位置,適用於大多數情境:它會以隱式 String 轉型或 str() 相同的方式轉換值。字串會保持不變,布林值會變成 "True""False",整數或浮點數會轉為十進位,其他類型則會轉為人類可讀的字串。

還有其他 格式規範 可用。

多重預留位置

格式化字串可以包含多個預留位置。此時,參數需以陣列方式傳入,每個預留位置對應一個值(除非使用 * 格式規範,請見 動態填充):

var format_string = "%s was reluctant to learn %s, but now he enjoys it."
var actual_string = format_string % ["Estragon", "GDScript"]

print(actual_string)
# Output: "Estragon was reluctant to learn GDScript, but now he enjoys it."

注意值會依序插入。請記得所有預留位置必須一次填滿,因此需要有正確數量的值。

格式規範

除了 s 之外,預留位置還可以使用其他格式規範。格式規範可以是一個或多個字元。有些像 s 一樣獨立使用,有些要搭配其他字元,有些則只適用於特定數值或字元。

預留位置類型

格式規範最後一定要有下表其中一個(且僅能有一個)。除了 s 之外,其他規範都需要特定型別的參數。

s

單純 以隱式 String 轉型的方式轉換為字串。

c

單一 Unicode 字元。需傳入 0-255 的無號 8 位元整數作為字碼指標,或單一字元的字串。

d

十進位整數。需傳入整數或浮點數(小數部分會被無條件捨去)。

o

八進位整數。需傳入整數或浮點數(小數部分會被無條件捨去)。

x

小寫 字母的 十六進位整數。需傳入整數或浮點數(小數部分會被無條件捨去)。

X

大寫 字母的 十六進位整數。需傳入整數或浮點數(小數部分會被無條件捨去)。

f

十進位實數。需傳入整數或浮點數。

v

向量。需傳入任一以整數或浮點數為基礎的向量物件(如 Vector2Vector3Vector4Vector2iVector3iVector4i)。會以括號顯示向量座標,每個座標會以 %f 方式格式化,且可套用相同修飾元。

預留位置修飾元

這些字元要放在格式規範前面。有些只在特定情況下有效。

+

在數字格式規範中,若為正數則 顯示 + 號

整數

設定 填充。若在整數或實數預留位置中以 0 開頭,則以 0 填充,否則以空白填充。若同時有 -,則忽略前導 0。若用於 . 之後,請見 . 說明。

.

fv 前面時,將 精度 設為 0 小數位。可以在後面加數字更改小數位數。以 0 進行填充。

-

向右填充,而非向左填充。

*

動態填充,會預期額外的整數參數來設定填充或 . 後的精度,請見 動態填充

填充

.``(點)、``*``(星號)、-(減號)及數字(``0-9)可用於填充。若搭配等寬字型,可讓多個值垂直對齊,像表格一樣。

若要將字串填充至最小長度,可在格式規範中加整數:

print("%10d" % 12345)
# output: "     12345"
# 5 leading spaces for a total length of 10

若整數以 0 開頭,則會以 0 填充整數值,而非空白:

print("%010d" % 12345)
# output: "0000012345"

對於實數,可在格式規範中加上 .``(點)及整數來指定精度。若 ``. 後未加數字,則精度為 0(四捨五入為整數)。用來填充的整數必須寫在點之前。

# Pad to minimum length of 10, round to 3 decimal places
print("%10.3f" % 10000.5555)
# Output: " 10000.556"
# 1 leading space

- 字元會讓填充改為向右(右對齊),方便右側對齊字串:

print("%-10d" % 12345678)
# Output: "12345678  "
# 2 trailing spaces

動態填充

使用 * (星號)可讓你不用修改格式化字串本身,就能動態設定填充或精度。它會取代格式規範中的整數,並於格式化時傳入填充或精度的數值:

var format_string = "%*.*f"
# Pad to length of 7, round to 3 decimal places:
print(format_string % [7, 3, 8.8888])
# Output: "  8.889"
# 2 leading spaces

若要在整數預留位置用 0 填充,則可在 * 前加上 0

print("%0*d" % [2, 3])
# Output: "03"

跳脫字元

若要將字面上的 % 字元插入格式化字串,必須跳脫它,避免被解析為預留位置。這可透過連續輸入兩個 % 達成:

var health = 56
print("Remaining health: %d%%" % health)
# Output: "Remaining health: 56%"

字串格式化方法

GDScript 也支援另一種格式化字串的方式,就是 String.format() 方法。它會將字串中出現的所有索引鍵,替換為對應的值。這個方法可以處理陣列或字典型態的索引鍵/值組。

陣列可以作為索引鍵、索引,或混合樣式使用(請見下方範例)。只有在用索引或混合樣式時才需注意順序。

GDScript 的簡易範例:

# Define a format string
var format_string = "We're waiting for {str}"

# Using the 'format' method, replace the 'str' placeholder
var actual_string = format_string.format({"str": "Godot"})

print(actual_string)
# Output: "We're waiting for Godot"

格式化方法範例

以下展示各種方式呼叫 String.format() 方法的範例。

型別

樣式

範例

結果

字典

索引鍵

"你好,{name} v{version}!".format({"name":"Godette", "version":"3.0"})

你好,Godette v3.0!

字典

索引

"你好,{0} v{1}!".format({"0":"Godette", "1":"3.0"})

你好,Godette v3.0!

字典

混合

"你好,{0} v{version}!".format({"0":"Godette", "version":"3.0"})

你好,Godette v3.0!

陣列

索引鍵

"你好,{name} v{version}!".format([["version","3.0"], ["name","Godette"]])

你好,Godette v3.0!

陣列

索引

"你好,{0} v{1}!".format(["Godette","3.0"])

你好,Godette v3.0!

陣列

混合

"你好,{name} v{0}!".format(["3.0", ["name","Godette"]])

你好,Godette v3.0!

陣列

無索引

"你好,{} v{}!".format(["Godette", "3.0"], "{}")

你好,Godette v3.0!

在使用 String.format 時也能自訂預留位置,下列為相關功能範例。

型別

範例

結果

中置(預設)

"你好,{0} v{1}".format(["Godette", "3.0"], "{_}")

你好,Godette v3.0

後置

"你好,0% v1%".format(["Godette", "3.0"], "_%")

你好,Godette v3.0

前置

"你好,%0 v%1".format(["Godette", "3.0"], "%_")

你好,Godette v3.0

有時可以同時使用 String.format 方法與 % 運算子,因為 String.format 無法直接調整數字格式。

範例

結果

"你好,{0} v{version}".format({0:"Godette", "version":"%0.2f" % 3.114})

你好,Godette v3.11

字串串接

你也可以用 + 運算子來將字串 串接 在一起。

# Define a base string
var base_string = "We're waiting for "

# Concatenate the string
var actual_string = base_string + "Godot"

print(actual_string)
# Output: "We're waiting for Godot"

在使用字串串接時,非字串的值必須先用 str() 函式轉換。這種方式無法指定轉換後數值的格式。

var name_string = "Godette"
var version = 3.0
var actual_string = "Hi, " + name_string + " v" + str(version) + "!"

print(actual_string)
# Output: "Hi, Godette v3!"

由於上述限制,格式化字串或 format() 方法通常會是更好的選擇。很多時候,字串串接也較難閱讀。

備註

在 Godot 的 C++ 程式碼中,可以透過 Variant 標頭裡的 vformat() 輔助函式來存取 GDScript 格式化字串。