Formatação de Strings em 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 {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.

Examine este exemplo concreto de 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 sempre começam com um %, mas o(s) próximo(s) caractere(s) o especificador de formato, determina como o valor dado é convertido em uma 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 int or float becomes a decimal, and other types usually return their data in a human-readable string.

There are other format specifiers.

Múltiplos espaços reservados

Strings de formatação podem conter múltiplos espaços reservados. Nesse caso, os valores são tratados na forma de um array, um valor para cada espaço reservado (a não ser que se use um especificador de formato com *, veja dynamic padding – "espaço de preenchimento dinâmico"):

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

Note que os valores são inseridos em ordem. Lembre-se que todos os espaços reservados devem ser substituídos de uma vez, para isso o numero de valores deve ser apropriado.

Especificadores de formato

Existem outros especificadores de formato além de s que podem ser usados nos espaços reservados. Eles consistem de um ou mais caracteres. Alguns dos quais funcionam por conta própria como ser s, alguns aparecem antes de outros caracteres, e alguns apenas funcionam com certos tipos de valores ou caracteres.

Tipos de espaços reservados

Apenas um destes deve sempre aparecer como o ultimo caractere em um especificador de formato. Diferentemente do s, estes requerem certos tipos de parâmetros.

s

Conversão simples para uma String pelo mesmo método que uma conversão implícita para String.

c

A single Unicode character. Accepts a Unicode code point (integer) or a single-character string. Supports values beyond 255.

d

A decimal integer. Expects an integer or a real number (will be floored).

o

An octal integer. Expects an integer or a real number (will be floored).

x

A hexadecimal integer with lower-case letters. Expects an integer or a real number (will be floored).

X

A hexadecimal integer with upper-case letters. Expects an integer or a real number (will be floored).

f

A decimal real number. Expects an integer or a real number.

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.

Modificadores temporários

Estes caracteres aparecem antes dos acima. Alguns deles só funcionam em certas condições.

+

Nos especificadores numéricos, mostra o simbolo + se positivo.

Inteiro

Defina o espaçamento. Espaçado com espaços ou com zeros se o número inteiro começa com 0 num número inteiro ou num número real com substituto. O principal 0 é ignorado se - estiver presente. Quando utilizado depois de ., veja ..

.

Before f or v, set precision to 0 decimal places. Can be followed up with numbers to change. Padded with zeroes.

-

Preencha para a direita ao invés da esquerda.

*

Dynamic padding, expects additional integer parameter to set padding or precision after ., see dynamic padding.

Preenchimento

Os caracteres . (ponto), * (asterisco), - (sinal negativo) e dígitos (0-9) são usados para preenchimento. Isso permite mostrar vários valores alinhados verticalmente, como se fosse uma coluna, desde que uma fonte de largura fixa seja usada.

Para preencher um texto com comprimento mínimo, acrescente um inteiro ao especificador:

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

O caractere - fará um preenchimento para a direita, em vez de à esquerda, sendo útil para o alinhamento do texto à direita:

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

Preenchimento dinâmico

Ao usar o caractere * (asterisco), o preenchimento ou a precisão podem ser definidos sem modificar o texto de formatação. Isso é usado no lugar de um inteiro no especificador de formato. Os valores para preenchimento e precisão serão então passados ao formatar:

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

É possível preencher com zeros nos locais reservados para inteiros ao adicionar 0 antes de *:

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

Sequência de escape

Para inserir um caractere % literal em um texto de formatação, ele deve ser escapado para evitar que seja lido como um espaço reservado. Isso é feito duplicando o caractere:

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.

Listas podem ser utilizadas como chave, index ou uma mistura de tipos (veja exemplos abaixo). A ordem importante apenas quando o Index ou a mistura de tipos da lista é utilizada.

Um exemplo rápido em 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"

Exemplos de métodos de formatação

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

Tipo

Estilo

Exemplo

Resultado

Dicionário

chave

"Olá, {nome} v{versao}!".format({"nome":"Godette", "versao":"3.0"})

Olá, Godette v3.0!

Dicionário

índice

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

Olá, Godette v3.0!

Dicionário

mistura

"Oi, {0} v{versao}!".format({"0":"Godette", "versao":"3.0"})

Olá, Godette v3.0!

Vetor

chave

"Oi, {nome} v{versao}!".format([["versao":"3.0"], ["nome":"Godette"]])

Olá, Godette v3.0!

Vetor

índice

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

Olá, Godette v3.0!

Vetor

mistura

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

Olá, Godette v3.0!

Vetor

sem índice

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

Olá, Godette v3.0!

Espaços reservados também podem ser personalizados utilizando String.format, aqui estão alguns exemplos dessa funcionalidade.

Tipo

Exemplo

Resultado

Infixo (padrão)

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

Oi, Godette v3.0

Pós-fixo

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

Oi, Godette v3.0

Prefixo

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

Oi, Godette v3.0

Combinar o método String.format e o operador % pode ser útil, já que String.format não possui uma maneira de manipular a representação de números.

Exemplo

Resultado

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

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