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."
Заповнювачі завжди починаються з символу %
, але наступний символ, або символи, специфікатор формату, вони визначають, як задане значення перетворюється на текст.
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.
Кілька заповнювачів
Форматований текст може містити кілька заповнювачів. У такому випадку значення передаються у вигляді масиву, одне значення на заповнювач (якщо не використовується специфікатор формату з *
, див. dynamic padding):
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
, для них потрібні певні типи параметрів.
|
Просте перетворення в String (текст, строку) тим самим методом, що і неявне перетворення. |
|
Єдиний символ Unicode. Очікує одне 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. |
|
Вектор. Очікує будь-який векторний об’єкт на основі float або int ( |
Модифікатори заповнювачів
Ці символи з'являються раніше. Деякі з них працюють лише за певних умов.
|
У специфікаторах чисел, **покажіть + знак**(show + sign), якщо число позитивне. |
Integer (ціле) |
Встановіть padding. Доповнюється пробілами або нулями, якщо ціле число починається з |
|
Перед |
|
Заповнення справа (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.
Тип |
Стиль |
Приклад |
Результат |
Словник |
ключ |
|
Привіт, Godette 3.0! |
Словник |
індекс |
|
Привіт, Godette 3.0! |
Словник |
суміш |
|
Привіт, Godette 3.0! |
Масив |
ключ |
|
Привіт, Godette 3.0! |
Масив |
індекс |
|
Привіт, Godette 3.0! |
Масив |
суміш |
|
Привіт, Godette 3.0! |
Масив |
без індекса |
|
Привіт, Godette 3.0! |
Заповнювачі також можуть бути налаштовані при використанні String.format
. Далі кілька прикладів цього функціоналу.
Тип |
Приклад |
Результат |
Інфікс (за замовчанням) |
|
Привіт, 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.