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

通过与隐式 String 转型的相同方法将传入的值 轻松转换为 String.

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

一个向量。需要任何浮点或基于整数的向量对象(Vector2Vector3Vector4Vector2iVector3iVector4i)。将在括号中显示向量坐标,将每个坐标格式化为 %f,并使用相同的修饰符。

占位符的修饰符

这些字符在上述占位符前出现. 其中一些只在特定情况下生效.

+

用在数字说明符中,如果为正数则显示 + 号

整数

设置填充。用空格填充,如果整数或实数占位符的整数部分以 0 开头则用零填充。存在 - 时会忽略开头的 0。当在 . 后使用时,请参阅 .

.

fv 之前,将精度十进制位设置为 0。可以跟上要更改精度的数字。用零填充。

-

在右侧填充而不是左侧。

*

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.

类型

样式

示例

结果

字典

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

Hi, Godette v3.0!

字典

索引

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

Hi, Godette v3.0!

字典

混合

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

Hi, Godette v3.0!

数组

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

Hi, Godette v3.0!

数组

索引

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

Hi, Godette v3.0!

数组

混合

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

Hi, Godette v3.0!

数组

没有索引

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

Hi, Godette v3.0!

使用 String.format 时, 也可以自定义占位符, 这是该功能的一些示例.

类型

示例

结果

中缀(默认)

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

Hi, Godette v3.0

后缀

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

Hi, Godette v3.0

前缀

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

Hi, Godette v3.0

结合 String.format 方法和 运算符可能很有用, 因为 String.format 没有办法操纵数字的表示.

示例

结果

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

Hi, 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.