String

Clase String integrada.

Descripción

Esta es la clase de string integrada (y la utilizada por GDScript). Soporta Unicode y proporciona todos los medios necesarios para el manejo de las strings. Las strings son contadas como referencia y usan un enfoque de copia sobre escritura, por lo que pasarlas es barato en recursos.

Tutoriales

Métodos

String

String ( bool from )

String

String ( int from )

String

String ( float from )

String

String ( Vector2 from )

String

String ( Rect2 from )

String

String ( Vector3 from )

String

String ( Transform2D from )

String

String ( Plane from )

String

String ( Quat from )

String

String ( AABB from )

String

String ( Basis from )

String

String ( Transform from )

String

String ( Color from )

String

String ( NodePath from )

String

String ( RID from )

String

String ( Dictionary from )

String

String ( Array from )

String

String ( PoolByteArray from )

String

String ( PoolIntArray from )

String

String ( PoolRealArray from )

String

String ( PoolStringArray from )

String

String ( PoolVector2Array from )

String

String ( PoolVector3Array from )

String

String ( PoolColorArray from )

bool

begins_with ( String text )

PoolStringArray

bigrams ( )

String

c_escape ( )

String

c_unescape ( )

String

capitalize ( )

int

casecmp_to ( String to )

int

count ( String what, int from=0, int to=0 )

int

countn ( String what, int from=0, int to=0 )

String

dedent ( )

bool

empty ( )

bool

ends_with ( String text )

void

erase ( int position, int chars )

int

find ( String what, int from=0 )

int

find_last ( String what )

int

findn ( String what, int from=0 )

String

format ( Variant values, String placeholder="{_}" )

String

get_base_dir ( )

String

get_basename ( )

String

get_extension ( )

String

get_file ( )

String

get_slice ( String delimiter, int slice )

int

hash ( )

int

hex_to_int ( )

String

http_escape ( )

String

http_unescape ( )

String

humanize_size ( int size )

String

indent ( String prefix )

String

insert ( int position, String what )

bool

is_abs_path ( )

bool

is_rel_path ( )

bool

is_subsequence_of ( String text )

bool

is_subsequence_ofi ( String text )

bool

is_valid_filename ( )

bool

is_valid_float ( )

bool

is_valid_hex_number ( bool with_prefix=false )

bool

is_valid_html_color ( )

bool

is_valid_identifier ( )

bool

is_valid_integer ( )

bool

is_valid_ip_address ( )

String

json_escape ( )

String

left ( int position )

int

length ( )

String

lstrip ( String chars )

bool

match ( String expr )

bool

matchn ( String expr )

PoolByteArray

md5_buffer ( )

String

md5_text ( )

int

naturalnocasecmp_to ( String to )

int

nocasecmp_to ( String to )

int

ord_at ( int at )

String

pad_decimals ( int digits )

String

pad_zeros ( int digits )

String

percent_decode ( )

String

percent_encode ( )

String

plus_file ( String file )

String

repeat ( int count )

String

replace ( String what, String forwhat )

String

replacen ( String what, String forwhat )

int

rfind ( String what, int from=-1 )

int

rfindn ( String what, int from=-1 )

String

right ( int position )

PoolStringArray

rsplit ( String delimiter, bool allow_empty=true, int maxsplit=0 )

String

rstrip ( String chars )

PoolByteArray

sha1_buffer ( )

String

sha1_text ( )

PoolByteArray

sha256_buffer ( )

String

sha256_text ( )

float

similarity ( String text )

String

simplify_path ( )

PoolStringArray

split ( String delimiter, bool allow_empty=true, int maxsplit=0 )

PoolRealArray

split_floats ( String delimiter, bool allow_empty=true )

String

strip_edges ( bool left=true, bool right=true )

String

strip_escapes ( )

String

substr ( int from, int len=-1 )

PoolByteArray

to_ascii ( )

float

to_float ( )

int

to_int ( )

String

to_lower ( )

String

to_upper ( )

PoolByteArray

to_utf8 ( )

PoolByteArray

to_wchar ( )

String

trim_prefix ( String prefix )

String

trim_suffix ( String suffix )

String

validate_node_name ( )

String

xml_escape ( )

String

xml_unescape ( )

Descripciones de Métodos

Construye una nueva String a partir del bool dado.


Construye un nuevo String a partir del int dado.


Construye una nueva string a partir del float dado.


Construye una nueva string a partir del Vector2 dado.


Construye una nueva String a partir del Rect2 dado.


Construye una nueva String a partir del Vector3 dado.


Construye un nuevo String a partir del dado Transform2D.


Construye una nueva String desde el Plane dado.


Construye una nueva String a partir del Quat dado.


Construye una nueva String a partir del AABB dado.


Construye una nueva String a partir de la Basis dada.


Construye un nuevo String a partir de la Transform dada.


Construye un nuevo String a partir del Color dado.


Construye un nuevo String a partir del NodePath dado.


Construye una nueva String a partir del RID dado.


Construye un nuevo String a partir del Dictionary dado.


Construye un nuevo String a partir del Array dado.


Constructs a new String from the given PoolByteArray.


Constructs a new String from the given PoolIntArray.


Constructs a new String from the given PoolRealArray.


Constructs a new String from the given PoolStringArray.


Constructs a new String from the given PoolVector2Array.


Constructs a new String from the given PoolVector3Array.


Constructs a new String from the given PoolColorArray.


Devuelve true si la string comienza con la string dada.


Devuelve los bigramas (pares de letras consecutivas) de esta string.


Devuelve una copia de la string con caracteres especiales escapados usando el estándar del lenguaje C.


Returns a copy of the string with escaped characters replaced by their meanings. Supported escape sequences are \', \", \?, \\, \a, \b, \f, \n, \r, \t, \v.

Note: Unlike the GDScript parser, this method doesn't support the \uXXXX escape sequence.


Cambia el caso de algunas cartas. Reemplaza los subrayados por espacios, añade espacios antes de los caracteres en mayúsculas, convierte todas las letras en minúsculas, luego pone en mayúsculas la primera letra y cada letra que sigue a un espacio. Para capitalize CamelCase mixed_with_underscores, devolverá Capitalize Camel Case Mixed With Underscores.


Performs a case-sensitive comparison to another string. Returns -1 if less than, 1 if greater than, or 0 if equal. "less than" or "greater than" are determined by the Unicode code points of each string, which roughly matches the alphabetical order.

Behavior with different string lengths: Returns 1 if the "base" string is longer than the to string or -1 if the "base" string is shorter than the to string. Keep in mind this length is determined by the number of Unicode codepoints, not the actual visible characters.

Behavior with empty strings: Returns -1 if the "base" string is empty, 1 if the to string is empty or 0 if both strings are empty.

To get a boolean result from a string comparison, use the == operator instead. See also nocasecmp_to.


Devuelve el número de ocurrencias de la substring what entre las posiciones de from y to. Si from y to es igual a 0 se utilizará la string completa. Si sólo a es igual a 0 se usará la substring restante.


Devuelve el número de ocurrencias de la substring what (ignorando el caso) entre las posiciones de from y to. Si from y to es igual a 0 se utilizará la string completa. Si sólo a es igual a 0 se usará la substring restante.


Returns a copy of the string with indentation (leading tabs and spaces) removed. See also indent to add indentation.


Devuelve true si la longitud de la string es igual a 0.


Devuelve true si la string termina con la string dada.


  • void erase ( int position, int chars )

Borra los caracteres chars de la string que comienza con position.


Finds the first occurrence of a substring. Returns the starting position of the substring or -1 if not found. Optionally, the initial search index can be passed.

Note: If you just want to know whether a string contains a substring, use the in operator as follows:

# Will evaluate to `false`.
if "i" in "team":
    pass

Finds the last occurrence of a substring. Returns the starting position of the substring or -1 if not found.


Finds the first occurrence of a substring, ignoring case. Returns the starting position of the substring or -1 if not found. Optionally, the initial search index can be passed.


Formatea la string reemplazando todas las ocurrencias de placeholder por values.


Si la string es una ruta de archivo válida, devuelve el nombre del directorio base.


Si la string es una ruta de archivo válida, devuelve la ruta de archivo completa sin la extensión.


Returns the extension without the leading period character (.) if the string is a valid file name or path. If the string does not contain an extension, returns an empty string instead.

print("/path/to/file.txt".get_extension())  # "txt"
print("file.txt".get_extension())  # "txt"
print("file.sample.txt".get_extension())  # "txt"
print(".txt".get_extension())  # "txt"
print("file.txt.".get_extension())  # "" (empty string)
print("file.txt..".get_extension())  # "" (empty string)
print("txt".get_extension())  # "" (empty string)
print("".get_extension())  # "" (empty string)

Si la string es una ruta de archivo válida, devuelve el nombre del archivo.


Splits a string using a delimiter and returns a substring at index slice. Returns an empty string if the index doesn't exist.

This is a more performant alternative to split for cases when you need only one element from the array at a fixed index.

Example:

print("i/am/example/string".get_slice("/", 2)) # Prints 'example'.

Hashea la string y devuelve un entero de 32 bits.


  • int hex_to_int ( )

Convierte una string que contiene un número hexadecimal en un entero. Se espera que las strings hexadecimales lleven el prefijo "0x", de lo contrario se devuelve 0.

print("0xff".hex_to_int()) # Imprimir "255"

Escapa (codifica) una string a un formato compatible con la URL. También conocido como 'codificación de URL'.

print("https://example.org/?escaped=" + "Godot Engine:'docs'".http_escape())

Desvincula (decodifica) una string en formato codificado de URL. También conocido como "decodificación de URL".

print("https://example.org/?escaped=" + "Godot%20Motor%3A%27docs%27".http_unescape())

Convierte el size representado como número de bytes a un formato legible para el ser humano utilizando un conjunto de unidades de tamaño de datos internacionalizados, a saber: B, KiB, MiB, GiB, TiB, PiB, EiB. Nótese que la siguiente unidad más pequeña es escogida automáticamente para contener como máximo 1024 unidades.

var bytes = 133790307
var size = String.humanize_size(bytes)
print(size) # imprime "127.5 MiB"

Returns a copy of the string with lines indented with prefix.

For example, the string can be indented with two tabs using "\t\t", or four spaces using "    ". The prefix can be any string so it can also be used to comment out strings with e.g. "# ". See also dedent to remove indentation.

Note: Empty lines are kept empty.


Devuelve una copia de la string con la substring what insertada en la posición dada.


  • bool is_abs_path ( )

Si la string es una ruta a un archivo o directorio, devuelve true si la ruta es absoluta.


  • bool is_rel_path ( )

Si la string es una ruta a un archivo o directorio, devuelve true si la ruta es relativa.


Devuelve true si esta string es una subsecuente de la string dada.


Devuelve true si esta string es una subsecuente de la string dada, sin considerar el caso.


  • bool is_valid_filename ( )

Devuelve true si esta string está libre de caracteres que no están permitidos en los nombres de los archivos, que son:

: / \ ? * " | % < >


  • bool is_valid_float ( )

Devuelve true si esta string contiene un real válido.


  • bool is_valid_hex_number ( bool with_prefix=false )

Devuelve true si esta string contiene un número hexadecimal válido. Si with_prefix es true, entonces la validez del número hexadecimal está determinada por el prefijo 0x, por ejemplo: 0xDEADC0DE.


  • bool is_valid_html_color ( )

Devuelve true si esta cadena contiene un color válido en notación HTML hexadecimal. Otras notaciones HTML como colores con nombre o colores hsl() no se consideran válidas por este método y devolverán false.


  • bool is_valid_identifier ( )

Devuelve true si esta string es un identificador válido. Un identificador válido sólo puede contener letras, dígitos y guiones bajos (_) y el primer carácter no puede ser un dígito.


  • bool is_valid_integer ( )

Devuelve true si esta string contiene un entero válido.


  • bool is_valid_ip_address ( )

Returns true if this string contains only a well-formatted IPv4 or IPv6 address. This method considers reserved IP addresses such as 0.0.0.0 as valid.


Devuelve una copia de la string con caracteres especiales escapados usando el estándar JSON.


Devuelve un número de caracteres de la izquierda de la string.


  • int length ( )

Devuelve la cantidad de caracteres de la string.


Returns a copy of the string with characters removed from the left. The chars argument is a string specifying the set of characters to be removed.

Note: The chars is not a prefix. See trim_prefix method that will remove a single prefix string rather than a set of characters.


Hace una comparación simple con expresión que distingue entre mayúsculas y minúsculas, en la que "*" coincide con cero o más caracteres arbitrarios y "?" coincide con cualquier carácter individual excepto con un punto (".").


Hace una simple comparación expresión insensible a las mayúsculas y minúsculas, en la que "*" coincide con cero o más caracteres arbitrarios y "?" coincide con cualquier carácter individual excepto con un punto (".").


Devuelve el hash MD5 de la string como un conjunto de bytes.


Devuelve el hash MD5 de la string como una string.


Performs a case-insensitive natural order comparison to another string. Returns -1 if less than, 1 if greater than, or 0 if equal. "less than" or "greater than" are determined by the Unicode code points of each string, which roughly matches the alphabetical order. Internally, lowercase characters will be converted to uppercase during the comparison.

When used for sorting, natural order comparison will order suites of numbers as expected by most people. If you sort the numbers from 1 to 10 using natural order, you will get [1, 2, 3, ...] instead of [1, 10, 2, 3, ...].

Behavior with different string lengths: Returns 1 if the "base" string is longer than the to string or -1 if the "base" string is shorter than the to string. Keep in mind this length is determined by the number of Unicode codepoints, not the actual visible characters.

Behavior with empty strings: Returns -1 if the "base" string is empty, 1 if the to string is empty or 0 if both strings are empty.

To get a boolean result from a string comparison, use the == operator instead. See also nocasecmp_to and casecmp_to.


Performs a case-insensitive comparison to another string. Returns -1 if less than, 1 if greater than, or 0 if equal. "less than" or "greater than" are determined by the Unicode code points of each string, which roughly matches the alphabetical order. Internally, lowercase characters will be converted to uppercase during the comparison.

Behavior with different string lengths: Returns 1 if the "base" string is longer than the to string or -1 if the "base" string is shorter than the to string. Keep in mind this length is determined by the number of Unicode codepoints, not the actual visible characters.

Behavior with empty strings: Returns -1 if the "base" string is empty, 1 if the to string is empty or 0 if both strings are empty.

To get a boolean result from a string comparison, use the == operator instead. See also casecmp_to.


Devuelve el código de caracteres en la posición at.


Formatea un número para tener un número exacto de digits después del punto decimal.


Formatea un número para tener un número exacto de digits después del punto decimal.


Decodificar una string de porcentaje codificado. Ver percent_encode.


Percent-encodes una string. Codifica los parámetros en una URL enviadon una solicitud HTTP GET (y los cuerpos de form-urlencoded POST requests).


Si la string es un camino, esto concatena file al final del string como un sub camino. Por ejemplo, "this/is".plus_file("path") == "this/is/path".


Devuelve la string original repetida varias veces. El número de repeticiones viene dado por el argumento.


Reemplaza las ocurrencias de una substring que distingue entre mayúsculas y minúsculas con la dada dentro de la string.


Reemplaza las ocurrencias de una substring insensible a las mayúsculas y minúsculas con la dada dentro de la string.


Performs a case-sensitive search for a substring, but starts from the end of the string instead of the beginning.


Performs a case-insensitive search for a substring, but starts from the end of the string instead of the beginning.


Devuelve el lado derecho de la string desde una posición determinada.


Divide la string por un string de delimiter y devuelve un array de substrings, empezando por la derecha.

Las divisiones en el array devuelto se ordenan en el mismo orden que la string original, de izquierda a derecha.

Si se especifica maxsplit, define el número de divisiones a realizar desde la derecha hasta maxsplit. El valor por defecto de 0 significa que todos los elementos se dividen, dando así el mismo resultado que split.

Ejemplo:

var some_string = "One,Two,Three,Four"
var some_array = some_string.rsplit(",", true, 1)
print(some_array.size()) # Imprime 2
print(some_array[0]) # Imprime "Cuatro"
print(some_array[1]) # Imprime "Three,Two,One"

Returns a copy of the string with characters removed from the right. The chars argument is a string specifying the set of characters to be removed.

Note: The chars is not a suffix. See trim_suffix method that will remove a single suffix string rather than a set of characters.


Devuelve el hash SHA-1 de la string como un conjunto de bytes.


Devuelve el hash del SHA-1 de la string como una string.


Devuelve el hash SHA-256 de la string como un array de bytes.


Devuelve el hash SHA-256 de la string como una string.


Devuelve el índice de similitud del texto comparado con esta string. 1 significa totalmente similar y 0 significa totalmente diferente.


Returns a simplified canonical path.


Splits the string by a delimiter string and returns an array of the substrings. The delimiter can be of any length.

If maxsplit is specified, it defines the number of splits to do from the left up to maxsplit. The default value of 0 means that all items are split.

If you need only one element from the array at a specific index, get_slice is a more performant option.

Example:

var some_string = "One,Two,Three,Four"
var some_array = some_string.split(",", true, 1)
print(some_array.size()) # Prints 2
print(some_array[0]) # Prints "One"
print(some_array[1]) # Prints "Two,Three,Four"

If you need to split strings with more complex rules, use the RegEx class instead.


Divide la string en reales usando una string delimitadora y devuelve un array de las substrings..

Por ejemplo, "1,2.5,3" devolverá [1,2.5,3] si se divide por ",".


Devuelve una copia de la string despojada de cualquier carácter no imprimible (incluyendo tabulaciones, espacios y saltos de línea) al principio y al final. Los argumentos opcionales se utilizan para conmutar la eliminación de la string en los bordes izquierdo y derecho respectivamente


Returns a copy of the string stripped of any escape character. These include all non-printable control characters of the first page of the ASCII table (< 32), such as tabulation (\t in C) and newline (\n and \r) characters, but not spaces.


Devuelve parte de la string de la posición from con la longitud len. El argumento len es opcional y usando -1 devolverá los caracteres restantes de la posición dada.


Converts the String (which is a character array) to PoolByteArray (which is an array of bytes). The conversion is faster compared to to_utf8, as this method assumes that all the characters in the String are ASCII characters.


Convierte una cadena que contiene un número decimal en un float.


  • int to_int ( )

Convierte una string que contiene un número entero en un int.


Devuelve la string convertida en minúsculas.


Devuelve la string convertida en mayúsculas.


Converts the String (which is an array of characters) to PoolByteArray (which is an array of bytes). The conversion is a bit slower than to_ascii, but supports all UTF-8 characters. Therefore, you should prefer this function over to_ascii.


Converts the String (which is an array of characters) to PoolByteArray (which is an array of bytes).


Elimina una determinada string desde el principio si empieza con ella o deja la string sin cambios.


Elimina una determinada string del final si termina con ella o deja la string sin cambios.


  • String validate_node_name ( )

Removes any characters from the string that are prohibited in Node names (. : @ / ").


Devuelve una copia de la string con caracteres especiales escapados usando el estándar XML.


Devuelve una copia de la string con los caracteres escapados reemplazados por sus significados según el estándar XML.