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...
Cadenas de formato en 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.
Mira este ejemplo concreto 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."
Los parámetros siempre comienzan con %
, pero el siguiente caracter o caracteres, el format specifier determina cómo el valor será convertido a cadena.
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.
Parámetros múltiples
Las cadenas de formato pueden contener múltiples variables. En cuyo caso, los valores son manejados en forma de array, un valor por variable (a menos que se utilice un especificador de formato con un *
, ver Rellenador Dinamico):
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."
Observa que los valores se insertan en orden. Recuerda que todos los marcadores de posición deben ser reemplazados a la vez, por lo que debe haber un número apropiado de valores.
Especificadores de formato
Existen otros especificadores de formato aparte de s
que pueden ser utilizado en parámetros. Estos consisten de uno o más caracteres. Algunos de ellos trabajan por sí mismos, como s
, algunos se colocan antes que otros caracteres, otros sólo funcionan con ciertos valores o caracteres.
Tipos de parámetros
Uno y sólo uno de estos debe aparecer como último caracter en un especificador de formato. Aparde de s
, estos requieren ciertos tipos de parámetros.
|
Conversión simple a cadena (string) por el mismo método que una conversión implícita en cadena. |
|
Caracter Unicode simple. Espera un entero sin signo de 8 bits (unsigned 8-bit integer, 0-255) para un código de posición o una cadena de caracteres simple. |
|
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. |
|
A vector. Expects any float or int-based vector object (
|
Modificadores de parámetros
Estos caracteres aparecen antes de los mencionados anteriormente. Algunos de ellos sólo funcionan bajo ciertas condiciones.
|
En especificadores numéricos, muestra el signo + si es positivo. |
Entero |
Define el padding. Rellenado con espacios o ceros si el entero comienza con |
|
Before |
|
Rellena a la derecha, en lugar de la izquierda. |
|
Dynamic padding, expects additional integer parameter to set
padding or precision after |
Relleno
Los caracteres .
(punto), *
(asterisco), -
(signo menos) y dígitos (0
-9
) son utilizados para relleno. Esto permite imprimir valores alineados verticalmente como en una columna, siempre que se utilice una fuente con ancho fijo.
Para rellenar una cadena a una longitud mínima, añade un número entero al specifier:
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
El caracter -
provocará un relleno a la derecha en vez de la izquierda, útil para alineo de texto a la derecha:
print("%-10d" % 12345678)
# Output: "12345678 "
# 2 trailing spaces
Relleno dinámico
Al utilizar el caracter *
(asterisco), el relleno o precisión podrán especificarse sin modificar la cadena string. Se usa en vez de un entero en el format specifier. Los valores para relleno y precisión son pasados al aplicarse el formato:
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 posible rellenar con ceros en las variables enteras agregando 0
antes del *
:
print("%0*d" % [2, 3])
# Output: "03"
Secuencias de escape
Para insertar un carácter literal %
dentro de una format string, debe "escaparse" para impedir que se lea como variable. Esto se consigue duplicando el carácter:
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.
Los arrays pueden ser utilizados como clave, índice o estilo mixto (ver ejemplos a continuación). El orden sólo importa cuando se utiliza el índice o el estilo mixto del Array.
Un ejemplo rápido 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"
Ejemplos de métodos de formateo
The following are some examples of how to use the various invocations of the
String.format()
method.
Tipo |
Estilo |
Ejemplo |
Resultado |
Diccionario |
clave |
|
Hola, Godette v3.0! |
Diccionario |
índice |
|
Hola, Godette v3.0! |
Diccionario |
mezcla |
|
Hola, Godette v3.0! |
Arreglo |
clave |
|
Hola, Godette v3.0! |
Arreglo |
índice |
|
Hola, Godette v3.0! |
Arreglo |
mezcla |
|
Hola, Godette v3.0! |
Arreglo |
sin índice |
|
Hola, Godette v3.0! |
Los parámetros pueden ser personalizados cuando se utiliza String.format
, aquí hay unos ejemplos sobre esa funcionalidad.
Tipo |
Ejemplo |
Resultado |
Infijo (por defecto) |
|
Hola, Godette v3.0 |
Sufijo |
|
Hola, Godette v3.0 |
Prefijo |
|
Hola, Godette v3.0 |
Combinar el método String.format
y el operador %
puede ser útil ya que String.format
no tiene un modo de manipular la representación de números.
Ejemplo |
Resultado |
|
Hola, 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.
Nota
In Godot's C++ code, GDScript format strings can be accessed using the
vformat()
helper function in the Variant header.