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.
Checking the stable version of the documentation...
Форматирование строки 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."
Заполнители всегда начинаются с %
, но следующий символ или символы, format specifier, определяют, как данное значение преобразуется в строку.
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
, они требуют определенные типы параметров.
|
Simple преобразование в строку осуществляется тем же методом, что и неявное преобразование строки. |
|
Unicode character. Ожидает одно 8-разрядное целое число без знака (0-255) таблицы символов или односимвольную строку. |
|
A decimal integer. Expects an integer or a real number (will be floored). |
|
An octal integer. Expects an integer or a real number (will be floored). |
|
A hexadecimal integer with lower-case letters. Expects an integer or a real number (will be floored). |
|
A hexadecimal integer with upper-case letters. Expects an integer or a real number (will be floored). |
|
A decimal real number. Expects an integer or a real number. |
|
A vector. Expects any float or int-based vector object (
|
Модификаторы-заполнители
Эти символы появляются перед вышеуказанными. Некоторые из них работают только при определенных условиях.
|
В спецификаторах чисел, show + sign показывает знак + если число положительное. |
Integer |
Set padding. Padded with spaces or with zeroes if integer
starts with |
|
Before |
|
Pad to the right заполнение справа, а не слева. |
|
Dynamic padding, expects additional integer parameter to set
padding or precision after |
Отступ
Символы .
(точка), *
(звездочка), -
(знак минус) и цифры (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
перед *
:
print("%0*d" % [2, 3])
# Output: "03"
Escape-последовательность
Чтобы вставить литерал %
в строку форматирования, он должен быть экранирован, чтобы не читать его в качестве заполнителя. Это делается путем дублирования символа:
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({"имя":"Godette", "версия":"3.0"}) |
Привет, Godette v3.0! |
Словарь |
индекс |
"Привет, {0} v{1}!".format({"0":"Godette", "1":"3.0"}) |
Привет, Godette v3.0! |
Словарь |
Сочетание |
|
Привет, Godette v3.0! |
Массив |
ключ |
|
Привет, Godette v3.0! |
Массив |
индекс |
|
Привет, Godette v3.0! |
Массив |
Сочетание |
|
Привет, Godette v3.0! |
Массив |
без индекса |
|
Привет, Godette v3.0! |
Заполнители также могут быть настроены при использовании String.format
. Вот несколько примеров этого функционала.
Тип |
Пример |
Результат |
Infix (по умолчанию) |
|
Привет, Godette v3.0 |
Постфикс |
|
Привет, Godette v3.0 |
Префикс |
|
Привет, Godette v3.0 |
Полезно использовать комбинацию String.format
и оператора %
, так как String.format
не предоставляет возможности управлять представлением чисел.
Пример |
Результат |
|
Привет, 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.