Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

GDScript formatuje łańcuchy znaków (string)

GDScript offers a feature called format strings, which allows reusing text templates to succinctly create different but similar strings.

Formatowane łańcuchy znaków są zwykł ciągami, z wyjątkiem tego, że zawierają pewne sekwencje znaków zastępczych. Te pola wyboru można łatwo zastąpić parametrami przekazanymi do formatowanego łańcucha.

As an example, with %s as a placeholder, the format string "Hello %s, how are you?" can easily be changed to "Hello World, how are you?". Notice the placeholder is in the middle of the string; modifying it without format strings could be cumbersome.

Zastosowanie w GDScript

Przeanalizujemy ten konkretny przykład 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."

Znaki specjalne zawsze zaczynają się od %, ale następnie musi być znak lub znaki, typ formatu, określa jak dana wartość jest konwertowana do typu string(łańcuch/ciąg znaków).

%s widoczne w przykładzie powyżej jest najprostszym symbolem zastępczym i działa dla większości przypadków: konwertuje wartość tą samą metodą, którą skonwertowałaby niejawna konwersja lub str(). Łańcuchy znaków pozostają niezmienione, wartości logiczne zmieniają się w "True" albo "False", liczby całkowite lub rzeczywiste stają się dziesiętnymi, pozostałe typy zwykle zwracają swoje dane w postaci czytelnego dla człowieka ciągu znaków.

Jest jeszcze inny sposób by sformatować tekst w GDScript, mianowicie za pomocą metody String.format(). Zamienia ona wszystkie wystąpienia klucza w łańcuchu znaków na odpowiednią wartość. Ta metoda pozwala na obsługę tablic, czy słowników dla par klucz/wartość.

Tablice mogą być używane jako klucz, indeks, lub w pomieszanym stylu (zobacz poniższe przykłady). Kolejność ma znaczenie tylko wtedy, gdy tablica jest użyta jako indeks lub w pomieszanym stylu.

Krótki przykład w 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"

There are other format specifiers, but they are only applicable when using the % operator.

Multiple placeholders

Format strings may contain multiple placeholders. In such a case, the values are handed in the form of an array, one value per placeholder (unless using a format specifier with *, see 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."

Zauważ, że wartości są wkładane w kolejności. Pamiętaj, że wszystkie symbole zastępcze muszą być zamieniane jednocześnie, więc musi być odpowiednia liczba wartości.

Specyfikatory formatowania

Istnieją specyfikatory formatowania inne niż s które mogą być użyte jako symbole zastępcze. Składają się z jednego lub więcej znaków. Niektóre z nich występują osobno jak s, inne pojawiają się przed innymi znakami, inne działają tylko z konkretnymi wartościami lub znakami.

Typy symboli zastępczych

One and only one of these must always appear as the last character in a format specifier. Apart from s, these require certain types of parameters.

s

Prosta konwersja na String przez tę samą metodę co domniemana konwersja.

c

Pojedynczy znak Unicode. Oczekuje 8-bitowej liczby całkowitej, bez znaku (0-255) jako punkt kodu lub jedno-znakowy String.

d

Liczba całkowita w systemie dziesiętnym. Oczekuje liczby całkowitej lub rzeczywistej(zostanie zaokrąglona w dół).

o

Liczba całkowita w systemie ósemkowym. Oczekuje liczby całkowitej lub rzeczywistej (zostanie zaokrąglona w dół).

x

Liczba całkowita w systemie szesnastkowym z **małymi literami. Oczekuje liczby całkowite lub rzeczywistej (zostanie zaokrąglona w dół).

X

Liczba całkowita w systemie szesnastkowym z wielkimi literami. Oczekuje liczby całkowitej lub rzeczywistej (zostanie zaokrąglona).

f

Liczba rzeczywista w systemie dziesiętnym. Oczekuje liczby całkowitej lub rzeczywistej.

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.

Modyfikatory symboli zastępczych

These characters appear before the above. Some of them work only under certain conditions.

+

In number specifiers, show + sign if positive.

Liczba całkowita

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.

-

Pad to the right rather than the left.

*

Dynamic padding, expect additional integral parameter to set padding or precision after ., see dynamic padding.

Wyrównanie

The . (dot), * (asterisk), - (minus sign) and digit (0-9) characters are used for padding. This allows printing several values aligned vertically as if in a column, provided a fixed-width font is used.

To pad a string to a minimum length, add an integer to the specifier:

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

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

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

Precyzję można określić dla liczb rzeczywistych przez dodanie . (kropki) z następującą po nim liczbą całkowitą. Bez liczby całkowitej po ., stosuje się dokładność 0, zaokrąglając do wartości całkowanej.

# Pad to minimum length of 10, round to 3 decimal places
print("%10.3f" % 10000.5555)
# Output: " 10000.556"
# 1 leading space

Znak - spowoduje przesunięcie w prawo, a nie w lewo, przydatne do wyrównania tekstu w prawo:

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

Dynamiczne wypełnienie

By using the * (asterisk) character, the padding or precision can be set without modifying the format string. It is used in place of an integer in the format specifier. The values for padding and precision are then passed when formatting:

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

It is still possible to pad with zeroes in integer placeholders by adding 0 before *:

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

Escape sequence

To insert a literal % character into a format string, it must be escaped to avoid reading it as a placeholder. This is done by doubling the character:

var health = 56
print("Remaining health: %d%%" % health)
# Output: "Remaining health: 56%"

Format method examples

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

Typ

Styl

Przykład

Wynik

Słownik

klucz

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

Hej, Godette v3.0!

Słownik

indeks

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

Hej, Godette v3.0!

Słownik

połączyć

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

Hej, Godette v3.0!

Tablica

klucz

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

Hej, Godette v3.0!

Tablica

indeks

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

Hej, Godette v3.0!

Tablica

połączyć

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

Hej, Godette v3.0!

Tablica

no index

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

Hej, Godette v3.0!

Placeholders can also be customized when using String.format, here's some examples of that functionality.

Typ

Przykład

Wynik

Infix (default)

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

Hej, Godette v3.0

Postfiks

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

Hej, Godette v3.0

Przedrostek

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

Hej, Godette v3.0

Combining both the String.format method and the % operator could be useful, as String.format does not have a way to manipulate the representation of numbers.

Przykład

Wynik

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

Hej, Godette v3.11