GDScript Format-Strings
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 {0} 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.
Versuchen Sie, das folgende GDScript-Beispiel zu verstehen:
# 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."
Platzhalter starten immer mit einem %, aber das nächste oder die nächsten Zeichen, der Formatkennzeichner, legt fest, wie der gegebene Wert zu einem String konvertiert wird.
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.
Mehrere Platzhalter
Format-Strings können mehrere Platzhalter enthalten. In diesem Fall werden die Werte in der Form eines Arrays gehandhabt, ein Wert pro Platzhalter (außer es wird ein Formatbezeichner mit * genutzt, siehe dynamisches 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."
Beachten Sie, dass die Werte der Reihe nach eingefügt werden. Denken Sie daran, dass alle Platzhalter auf einmal ersetzt werden müssen, es muss also eine angemessene Anzahl von Werten vorhanden sein.
Formatbezeichner
Es gibt weitere Formatbezeichner außer s, die in Platzhaltern genutzt werden können. Diese bestehen aus einem oder mehreren Zeichen. Manche funktionieren für sich alleine, wie s, manche stehen vor anderen Zeichen, wieder andere funktionieren in Verbindung mit bestimmten Werten oder Zeichen.
Platzhalter-Typen
Einer – und nur einer – dieser Platzhalter-Typen muss immer als letztes Zeichen in einem Formatbezeichner auftreten. Abgesehen von s werden bestimmte Parametertypen benötigt.
|
Einfache Konvertierung von einem String mit der selben Methode, die bei der impliziten String-Konvertierung verwendet wird. |
|
Ein einzelnes Unicode-Zeichen. Erwartet ein unsigned 8-bit Integer (0-255) für einen Codepunkt oder einen String, der aus einem einzelnen Zeichen besteht. |
|
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. |
|
Ein Vektor. Erwartet ein beliebiges float- oder int-basiertes Vektorobjekt ( |
Platzhalter-Modifikatoren
Diese Zeichen erscheinen vor den oben angegebenen. Einige davon funktionieren nur unter bestimmten Bedingungen.
|
Gibt bei Zahlen-Bezeichnern das ** "+"-Vorzeichen mit an**, falls die Zahl positiv ist. |
Integer |
Padding einstellen. Füllt bei einem Platzhalter für ganze oder reelle Zahlen den String mit Leerzeichen oder Nullen auf, wenn die ganze Zahl mit |
|
Vor |
|
Rechts-Padding statt Links-Padding. |
|
Dynamic padding, expects additional integer parameter to set
padding or precision after |
Padding
Die Zeichen . (Punkt), * (Stern), - (Minuszeichen) und Ziffer (0-9) werden zum Padding verwendet. Auf diese Weise können mehrere Werte vertikal angeordnet werden, als wären sie in einer Spalte, sofern eine Schriftart mit fester Breite verwendet wird.
Um einen String auf eine Minimallänge zu padden, fügen Sie eine Ganzzahl zum Bezeichner hinzu:
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
Das Zeichen - führt zu einem Rechts-Padding statt einem Links-Padding, was nützlich ist für rechts ausgerichteten Text:
print("%-10d" % 12345678)
# Output: "12345678 "
# 2 trailing spaces
Dynamisches Padding
Mit dem Zeichen * (Stern) kann der Abstand oder die Genauigkeit festgelegt werden, ohne den Formatstring zu ändern. Es wird anstelle einer Ganzzahl im Formatbezeichner verwendet. Die Werte für Padding und Genauigkeit werden dann beim Formatieren übergeben:
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
Es ist weiterhin möglich, Ganzzahl-Platzhalter mit Nullen aufzufüllen, indem 0 vor * eingefügt wird:
print("%0*d" % [2, 3])
# Output: "03"
Escape-Sequenz
Um ein Zeichen % selbst in einen Format-String einzubauen, muss dieses „escaped“ werden, damit es nicht als Platzhalter aufgefasst wird. Dies schafft man durch das Verdoppeln des Zeichens:
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.
Arrays können als Key, Index oder in gemischtem Stil (siehe Beispiele unten) vorkommen. Die Reihenfolge ist nur wichtig, wenn der Index oder der gemischte Stil des Arrays benutzt wird.
Ein kurzes Beispiel in 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"
Beispiele für Formatierungsmethoden
The following are some examples of how to use the various invocations of the
String.format() method.
Typ |
Stil |
Beispiel |
Ergebnis |
Dictionary |
Key |
|
Hallo, Godette v3.0! |
Dictionary |
Index |
|
Hallo, Godette v3.0! |
Dictionary |
gemischt |
|
Hallo, Godette v3.0! |
Array |
Key |
|
Hallo, Godette v3.0! |
Array |
Index |
|
Hallo, Godette v3.0! |
Array |
gemischt |
|
Hallo, Godette v3.0! |
Array |
kein Index |
|
Hallo, Godette v3.0! |
Platzhalter können auch bei Verwendung von String.format angepasst werden, hier einige Beispiele zu dieser Funktionalität.
Typ |
Beispiel |
Ergebnis |
Infix (Default) |
|
Hallo, Godette v3.0 |
Postfix |
|
Hallo, Godette v3.0 |
Präfix |
|
Hallo, Godette v3.0 |
Es kann sinnvoll sein, die String.format-Methode mit dem %-Operator zu kombinieren, da mit String.format keine Möglichkeit besteht, die Repräsentation von Zahlen zu beeinflussen.
Beispiel |
Ergebnis |
|
Hallo, 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.
Bemerkung
In Godot's C++ code, GDScript format strings can be accessed using the
vformat() helper function in the Variant header.