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...
Chaines de format 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.
Examinez cet exemple concret en 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."
Les emplacements réservés commencent toujours par un %
, mais le ou les caractères suivants, le spécificateur de format, détermine comment la valeur donnée est convertie en chaîne.
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.
Emplacements réservés multiples
Les chaînes de format peuvent contenir plusieurs emplacements réservés. Dans un tel cas, les valeurs sont présentées sous la forme d'un tableau, une valeur par emplacement réservé (sauf si vous utilisez un spécificateur de format avec *
, voir remplissage dynamique) :
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."
Notez que les valeurs sont insérées dans l'ordre. À chaque emplacement réservé doit correspondre une valeur. Pensez donc à passer le nombre de valeurs adéquat.
Les spécificateurs de format
Il existe des spécificateurs de format autres que s
qui peuvent être utilisés dans les emplacements réservés. Ils consistent en un ou plusieurs caractères. Certains d'entre eux fonctionnent par eux-mêmes comme s
, certains apparaissent avant les autres caractères, d'autres ne fonctionnent qu'avec certaines valeurs ou caractères.
Types d'emplacements réservés
Un et un seul d'entre eux doivent toujours apparaître en tant que dernier caractère dans un spécificateur de format. En dehors de s
, ceux-ci nécessitent certains types de paramètres.
|
Simple conversion en chaîne par la même méthode que la conversion implicite de chaîne. |
|
Un seul caractère Unicode. Attend un entier non signé 8 bits (0-255) pour un point de code ou une chaîne d'un seul caractère. |
|
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. |
|
Un vecteur. Attend tout objet vecteur de type float ou int ( |
Modificateurs d'emplacement réservé
Ces caractères apparaissent avant les précédents. Ils ne fonctionnent que sous certaines conditions.
|
Dans les spécificateurs de nombres, afficher le signe + si positif. |
Nombre entier |
Fixe le remplissage. Remplit avec des espaces ou des zéros si l'entier commence par |
|
Avant |
|
Remplissage à droite plutôt qu'à gauche. |
|
Dynamic padding, expects additional integer parameter to set
padding or precision after |
Remplissage(Padding)
Les caractères .
(point), *
(astérisque), -
(signe moins) et chiffres (0
-9
) sont utilisés pour le remplissage. Ceci permet d'imprimer plusieurs valeurs alignées verticalement comme dans une colonne, à condition d'utiliser une police à largeur fixe.
Pour remplir une chaîne jusqu'à une longueur minimale, ajoutez un entier au spécificateur :
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
Le caractère -
provoquera le remplissage à droite plutôt qu'à gauche, ce qui est utile pour l'alignement du texte :
print("%-10d" % 12345678)
# Output: "12345678 "
# 2 trailing spaces
Remplissage dynamique
En utilisant le caractère *
(astérisque), le remplissage ou la précision peuvent être réglés sans modifier la chaîne de format. Il est utilisé à la place d'un entier dans le spécificateur de format. Les valeurs pour le remplissage et la précision sont alors passées lors du formatage :
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
Il est toujours possible de remplir avec des zéros dans les spécificateurs de nombre entiers en ajoutant 0
avant *
:
print("%0*d" % [2, 3])
# Output: "03"
Séquence d'échappement
Pour insérer un caractère littéral %
dans une chaîne de formatage, il faut l'échapper pour éviter de le lire comme un caractère de remplacement. Cela se fait en doublant le caractère :
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.
Les tableaux peuvent être utilisés par clé, index ou en style mixte (voir les exemples ci-dessous). L'ordre n'a d'importance que lorsqu'on utilise l'index ou le style mixte de Array.
Un bref exemple en 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"
Exemples de méthodes de formatage
The following are some examples of how to use the various invocations of the
String.format()
method.
Type |
Style |
Exemple |
Résultat |
Dictionnaire |
clé |
|
Salut, Godette v3.0 ! |
Dictionnaire |
index, position |
|
Salut, Godette v3.0 ! |
Dictionnaire |
mixte |
|
Salut, Godette v3.0 ! |
Tableau |
clé |
|
Salut, Godette v3.0 ! |
Tableau |
index, position |
|
Salut, Godette v3.0 ! |
Tableau |
mixte |
|
Salut, Godette v3.0 ! |
Tableau |
pas d'index |
|
Salut, Godette v3.0 ! |
Les emplacements réservés peuvent également être personnalisés lors de l'utilisation de String.format
, voici quelques exemples de cette fonctionnalité.
Type |
Exemple |
Résultat |
Infixe (par défaut) |
|
Salut, Godette v3.0 |
Postfixe |
|
Salut, Godette v3.0 |
Préfixe |
|
Salut, Godette v3.0 |
Combiner la méthode String.format
et l'opérateur %
pourrait être utile puisque String.format
n'a pas de possibilité de manipuler une représentation numérique.
Exemple |
Résultat |
|
Salut, 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.
Note
In Godot's C++ code, GDScript format strings can be accessed using the
vformat()
helper function in the Variant header.