Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

GDScript 格式字串

Godot offers multiple ways to dynamically change the contents of strings:

  • Format strings: var string = "I have %s cats." % "3"

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

  • String concatenation: var string = "I have " + str(3) + " cats."

This page explains how to use format strings, and briefly explains the format() method and string concatenation.

Format strings

Format strings are a way to reuse text templates to succinctly create different but similar strings.

Format strings are just like normal strings, except they contain certain placeholder character sequences such as %s. These placeholders can then be replaced by parameters handed to the format string.

來看看這個實際的 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."

預留位置都以 % 開頭,而接下來的字元 —— 格式規範 —— 則用來判斷給定的數值要如何轉換為字串。

The %s seen in the example above is the simplest placeholder and works for most use cases: it converts the value by the same method by which an implicit String conversion or str() would convert it. Strings remain unchanged, booleans turn into either "True" or "False", an int or float becomes a decimal, and other types usually return their data in a human-readable string.

There are other format specifiers.

多預留位置

格式化字串可以包含多個預留位置。這時,數值必須以陣列形式來傳遞,一個數值一個預留位置 (除非使用 * 格式規範,請參見 動態填充 ):

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

使用與字串轉換方式相同的方法, 單純 將數值轉為字串。

c

單一 Unicode 字元 。需要輸入無號 8 位元整數 (0-255) 作為字碼指標或單一字元字串。

d

A decimal integer. Expects an integer or a real number (will be floored).

o

An octal integer. Expects an integer or a real number (will be floored).

x

A hexadecimal integer with lower-case letters. Expects an integer or a real number (will be floored).

X

A hexadecimal integer with upper-case letters. Expects an integer or a real number (will be floored).

f

A decimal real number. Expects an integer or a real number.

v

A vector. Expects any float or int-based vector object ( Vector2, Vector3, Vector4, Vector2i, Vector3i or Vector4i). Will display the vector coordinates in parentheses, formatting each coordinate as if it was an %f, and using the same modifiers.

預留位置修飾元

這些字元放置於上表中字串的前面。有部分修飾元只能在特定情況下使用。

+

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

整數

設定 填充。若該整數以 0 開頭則以 0 填充,否則以空白填充。若在 . 後使用,請參見 .

.

Before f or v, set precision to 0 decimal places. Can be followed up with numbers to change. Padded with zeroes.

-

向右填充 ,而非向左。

*

Dynamic padding, expects additional integer parameter to set padding or precision after ., see dynamic padding.

填充

. (), * (星號), - (減號) 與數字 (0-9) 可以用來填充。配合等寬字形使用可以在印出多個值時垂直對齊。

若要將字串填充至最小長度,可在規範字元前加上一個整數:

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

If the integer starts with 0, integer values are padded with zeroes instead of white space:

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

Precision can be specified for real numbers by adding a . (dot) with an integer following it. With no integer after ., a precision of 0 is used, rounding to integer values. The integer to use for padding must appear before the dot.

# 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%"

String format method

There is also another way to format text in GDScript, namely the String.format() method. It replaces all occurrences of a key in the string with the corresponding value. The method can handle arrays or dictionaries for the key/value pairs.

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

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"

格式化方法範例

The following are some examples of how to use the various invocations of the String.format() method.

型別

樣式

範例

結果

字典

索引鍵

"你好,{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!

陣列

混合

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

你好,Godette v3.0!

陣列

無索引

"Hi, {} 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

String concatenation

You can also combine strings by concatenating them together, using the + operator.

# 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"

When using string concatenation, values that are not strings must be converted using the str() function. There is no way to specify the string format of converted values.

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

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

Because of these limitations, format strings or the format() method are often a better choice. In many cases, string concatenation is also less readable.

備註

In Godot's C++ code, GDScript format strings can be accessed using the vformat() helper function in the Variant header.