Up to date

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

GDScript format strings

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

Format strings are just like normal strings, except they contain certain placeholder character-sequences. These placeholders can then easily be replaced by parameters handed to the format string.

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.

Utilizzo in GDScript

Esamina questo esempio concreto in 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."

Placeholders always start with a %, but the next character or characters, the format specifier, determines how the given value is converted to a string.

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 integral or real number becomes a decimal, other types usually return their data in a human-readable string.

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 can be used as key, index, or mixed style (see below examples). Order only matters when the index or mixed style of Array is used.

Un rapido esempio 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"

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

Segnaposto multipli

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

Nota che i valori sono inseriti in ordine. Ricorda che tutti i segnaposto devono essere rimpiazzati, quindi deve esserci un numero appropriato di valori.

Specificatore di formato

Ci sono altri specificatori di formato oltre a s che possono essere usati come segnaposto. Consistono in uno o più caratteri. Alcuni funzionano da soli come s, altri compaiono prima di altri caratteri e altri ancora funzionano con alcuni valori o caratteri.

Tipi di segnaposto

Uno e uno solo di questi deve sempre comparire come ultimo carattere in uno specificatore di formato. A parte s, questi richiedono certi tipi di parametri.

s

Semplice conversione a Stringa dallo stesso metodo della conversione implicita.

c

A single Unicode character. Expects an unsigned 8-bit integer (0-255) for a code point or a single-character string.

d

Un numero decimale intero. Si aspetta un intero o un numero reale (sarà troncato).

o

Un numero integrale ottale. Si aspetta un integrale o un numero reale (sarà troncato).

x

Un numero esadecimale intero con lettere minuscole. Si aspetta un intero o numero reale (verrà troncato).

X

Un numero esadecimale intero con lettere maiuscole. Si aspetta un intero o numero reale (verrà troncato).

f

Un numero decimale reale. Si aspetta un integrale o un numero reale.

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.

Modificatori segnaposto

Questi caratteri vengono visualizzati prima di quanto sopra. Alcuni di loro funzionano solo a determinate condizioni.

+

In number specifiers, show + sign if positive.

Numero intero

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.

Padding

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"

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 integral value. 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

The - character will cause padding to the right rather than the left, useful for right text alignment:

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

Dynamic padding

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

Esempi del metodo Format

I seguenti sono alcuni esempi di come usare le varie invocazioni del metodo String.format.

Tipo

Stile

Esempio

Risultato

Dizionario

chiave

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

Ciao, Godette v3.0!

Dizionario

indice

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

Ciao, Godette v3.0!

Dizionario

mix

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

Ciao, Godette v3.0!

Array

chiave

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

Ciao, Godette v3.0!

Array

indice

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

Ciao, Godette v3.0!

Array

mix

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

Ciao, Godette v3.0!

Array

no index

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

Ciao, Godette v3.0!

I segnaposto possono anche essere personalizzati quando si usa String.format, ecco alcuni esempi di questa funzionalità.

Tipo

Esempio

Risultato

Infix (default)

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

Ciao, Godette v3.0

Suffisso

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

Ciao, Godette v3.0

Prefisso

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

Ciao, 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.

Esempio

Risultato

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

Ciao, Godette v3.11