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.

Formátovací řetězce GDScriptu

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.

Prohlédněte si tento konkrétní příklad 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."

Zástupné znaky vždy začínají znakem %, ale další znak nebo znaky, specifikátor formátu, určují, jak bude daná hodnota převedena na řetězec.

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.

Více zástupných symbolů

Formátovací řetězce mohou obsahovat více zástupných znaků. V takovém případě jsou hodnoty předávány ve formě pole, jedna hodnota na každý zástupný znak (pokud není použit specifikátor formátu s *, viz dynamické vyplňování):

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

Všimněte si, že hodnoty jsou vkládány popořádku. Nezapomeňte, že všechny zástupné symboly musí být nahrazeny najednou, takže je potřeba i odpovídající počet hodnot.

Specifikátory formátu

V zástupných znacích lze použít i jiné specifikátory formátu než s. Skládají se z jednoho nebo více znaků. Některé z nich fungují samy o sobě podobně jako s, některé se objevují před jinými znaky, některé fungují pouze s určitými hodnotami nebo znaky.

Typy zástupných symbolů

Jeden a to právě jeden z nich se musí vždy objevit jako poslední znak ve specifikátoru formátu. Kromě s vyžadují všechny ostatní určité typy parametrů.

s

Jednoduchý převod na řetězec pomocí implicitní metody konverze na String.

c

Jeden znak Unicode. Očekává 8bitové celé číslo bez znaménka (0-255) pro codepoint nebo jednoznakový řetězec.

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.

Modifikátory zástupných symbolů

Tyto znaky se objevují před výše uvedenými. Některé z nich fungují pouze za určitých podmínek.

+

V číselných specifikátorech zobrazí znaménko +, pokud je kladné.

Číslo

Set padding. Padded with spaces or with zeroes if integer starts with 0 in an integer or real number placeholder. The leading 0 is ignored if - is present. When used after ., see ..

.

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

-

Zarovnává doprava, nikoli doleva.

*

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

Zarovnávání

Znaky .` (tečka), * (hvězdička), - (minus) a číslice (0-9) se používají pro zarovnávání. To umožňuje tisk několika hodnot zarovnaných vertikálně jako ve sloupci, pokud je použito písmo s pevnou šířkou.

Chcete-li řetězec zarovnat na minimální délku, přidejte ke specifikátoru celé číslo:

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

Znak - způsobí zarovnání vpravo, nikoli vlevo, což je užitečné pro zarovnávání textu vpravo:

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

Dynamické zarovnávání

Pomocí znaku *` (hvězdička) lze nastavit zarovnání nebo přesnost bez úpravy formátovacího řetězce. Používá se místo celého čísla ve specifikátoru formátu. Hodnoty pro zarovnání a přesnost se pak předávají při formátování:

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

V celočíselných zástupných znacích je stále možné zarovnávat nulami přidáním 0` před *:

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

Escape sekvence

Chcete-li do formátovacího řetězce vložit prostý znak %, je třeba jej escapovat. Tak se zabrání jeho čtení jako zástupného znaku. Toto se provádí zdvojením znaku:

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.

Pole lze použít s klíči nebo indexy, oba styly lze i kombinovat (viz příklady níže). Na pořadí záleží pouze při použití indexového nebo smíšeného stylu pole.

Rychlý příklad v 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"

Příklady formátovacích metod

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

Typ

Styl

Příklad

Výsledek

Slovník

klíč

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

Hi, Godette v3.0!

Slovník

index

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

Hi, Godette v3.0!

Slovník

mix

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

Hi, Godette v3.0!

Pole

klíč

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

Hi, Godette v3.0!

Pole

index

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

Hi, Godette v3.0!

Pole

mix

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

Hi, Godette v3.0!

Pole

žádný index

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

Hi, Godette v3.0!

Zástupné znaky lze také přizpůsobit pomocí String.format, zde je několik příkladů této funkce.

Typ

Příklad

Výsledek

Infix (výchozí)

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

Hi, Godette v3.0

Postfix

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

Hi, Godette v3.0

Prefix

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

Hi, Godette v3.0

Kombinace metody String.format a operátoru % by mohla být užitečná, protože String.format nemá možnost manipulovat s reprezentací čísel.

Příklad

Výsledek

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

Poznámka

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