String
A built-in type for strings.
Description
This is the built-in string Variant type (and the one used by GDScript). Strings may contain any number of Unicode characters, and expose methods useful for manipulating and generating strings. Strings are reference-counted and use a copy-on-write approach (every modification to a string returns a newString), so passing them around is cheap in resources.
Some string methods have corresponding variations. Variations suffixed withn
(countn(),findn(),replacen(), etc.) arecase-insensitive (they make no distinction between uppercase and lowercase letters). Method variations prefixed withr
(rfind(),rsplit(), etc.) are reversed, and start from the end of the string, instead of the beginning.
To convert anyVariant to or from a string, see@GlobalScope.str(),@GlobalScope.str_to_var(), and@GlobalScope.var_to_str().
Note: In a boolean context, a string will evaluate tofalse
if it is empty (""
). Otherwise, a string will always evaluate totrue
.
Note
There are notable differences when using this API with C#. SeeC# API differences to GDScript for more information.
Tutorials
Constructors
String() | |
String(from:StringName) |
Methods
begins_with(text:String)const | |
get_slice_count(delimiter:String)const | |
get_slicec(delimiter:int, slice:int)const | |
humanize_size(size:int)static | |
is_subsequence_of(text:String)const | |
is_valid_hex_number(with_prefix:bool = false)const | |
join(parts:PackedStringArray)const | |
num_int64(number:int, base:int = 10, capitalize_hex:bool = false)static | |
num_scientific(number:float)static | |
num_uint64(number:int, base:int = 10, capitalize_hex:bool = false)static | |
pad_decimals(digits:int)const | |
rsplit(delimiter:String = "", allow_empty:bool = true, maxsplit:int = 0)const | |
similarity(text:String)const | |
split(delimiter:String = "", allow_empty:bool = true, maxsplit:int = 0)const | |
split_floats(delimiter:String, allow_empty:bool = true)const | |
strip_edges(left:bool = true, right:bool = true)const | |
trim_prefix(prefix:String)const | |
trim_suffix(suffix:String)const | |
unicode_at(at:int)const | |
xml_escape(escape_quotes:bool = false)const | |
Operators
operator !=(right:String) | |
operator !=(right:StringName) | |
operator %(right:Variant) | |
operator +(right:String) | |
operator +(right:StringName) | |
operator <(right:String) | |
operator <=(right:String) | |
operator ==(right:String) | |
operator ==(right:StringName) | |
operator >(right:String) | |
operator >=(right:String) | |
operator [](index:int) |
Constructor Descriptions
Constructs an emptyString (""
).
Constructs aString as a copy of the givenString.
Constructs a newString from the givenNodePath.
StringString(from:StringName)
Constructs a newString from the givenStringName.
Method Descriptions
boolbegins_with(text:String)const🔗
Returnstrue
if the string begins with the giventext
. See alsoends_with().
PackedStringArraybigrams()const🔗
Returns an array containing the bigrams (pairs of consecutive characters) of this string.
print("Get up!".bigrams())# Prints ["Ge", "et", "t ", " u", "up", "p!"]
Converts the string representing a binary number into anint. The string may optionally be prefixed with"0b"
, and an additional-
prefix for negative numbers.
print("101".bin_to_int())# Prints 5print("0b101".bin_to_int())# Prints 5print("-0b10".bin_to_int())# Prints -2
GD.Print("101".BinToInt());// Prints 5GD.Print("0b101".BinToInt());// Prints 5GD.Print("-0b10".BinToInt());// Prints -2
Returns a copy of the string with special characters escaped using the C language standard.
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.
Changes the appearance of the string: replaces underscores (_
) with spaces, adds spaces before uppercase letters in the middle of a word, converts all letters to lowercase, then converts the first one and each one following a space to uppercase.
"move_local_x".capitalize()# Returns "Move Local X""sceneFile_path".capitalize()# Returns "Scene File Path""2D, FPS, PNG".capitalize()# Returns "2d, Fps, Png"
"move_local_x".Capitalize();// Returns "Move Local X""sceneFile_path".Capitalize();// Returns "Scene File Path""2D, FPS, PNG".Capitalize();// Returns "2d, Fps, Png"
intcasecmp_to(to:String)const🔗
Performs a case-sensitive comparison to another string. Returns-1
if less than,1
if greater than, or0
if equal. "Less than" and "greater than" are determined by theUnicode code points of each string, which roughly matches the alphabetical order.
With different string lengths, returns1
if this string is longer than theto
string, or-1
if shorter. Note that the length of empty strings isalways0
.
To get abool result from a string comparison, use the==
operator instead. See alsonocasecmp_to(),filecasecmp_to(), andnaturalcasecmp_to().
Returns a single Unicode character from the decimalchar
. You may useunicodelookup.com orunicode.org as points of reference.
print(String.chr(65))# Prints "A"print(String.chr(129302))# Prints "🤖" (robot face emoji)
boolcontains(what:String)const🔗
Returnstrue
if the string containswhat
. In GDScript, this corresponds to thein
operator.
print("Node".contains("de"))# Prints trueprint("team".contains("I"))# Prints falseprint("I"in"team")# Prints false
GD.Print("Node".Contains("de"));// Prints TrueGD.Print("team".Contains("I"));// Prints False
If you need to know wherewhat
is within the string, usefind(). See alsocontainsn().
boolcontainsn(what:String)const🔗
Returnstrue
if the string containswhat
,ignoring case.
If you need to know wherewhat
is within the string, usefindn(). See alsocontains().
intcount(what:String, from:int = 0, to:int = 0)const🔗
Returns the number of occurrences of the substringwhat
betweenfrom
andto
positions. Ifto
is 0, the search continues until the end of the string.
intcountn(what:String, from:int = 0, to:int = 0)const🔗
Returns the number of occurrences of the substringwhat
betweenfrom
andto
positions,ignoring case. Ifto
is 0, the search continues until the end of the string.
Returns a copy of the string with indentation (leading tabs and spaces) removed. See alsoindent() to add indentation.
boolends_with(text:String)const🔗
Returnstrue
if the string ends with the giventext
. See alsobegins_with().
Stringerase(position:int, chars:int = 1)const🔗
Returns a string withchars
characters erased starting fromposition
. Ifchars
goes beyond the string's length given the specifiedposition
, fewer characters will be erased from the returned string. Returns an empty string if eitherposition
orchars
is negative. Returns the original string unmodified ifchars
is0
.
intfilecasecmp_to(to:String)const🔗
Likenaturalcasecmp_to() but prioritizes strings that begin with periods (.
) and underscores (_
) before any other character. Useful when sorting folders or file names.
To get abool result from a string comparison, use the==
operator instead. See alsofilenocasecmp_to(),naturalcasecmp_to(), andcasecmp_to().
intfilenocasecmp_to(to:String)const🔗
Likenaturalnocasecmp_to() but prioritizes strings that begin with periods (.
) and underscores (_
) before any other character. Useful when sorting folders or file names.
To get abool result from a string comparison, use the==
operator instead. See alsofilecasecmp_to(),naturalnocasecmp_to(), andnocasecmp_to().
intfind(what:String, from:int = 0)const🔗
Returns the index of thefirst occurrence ofwhat
in this string, or-1
if there are none. The search's start can be specified withfrom
, continuing to the end of the string.
print("Team".find("I"))# Prints -1print("Potato".find("t"))# Prints 2print("Potato".find("t",3))# Prints 4print("Potato".find("t",5))# Prints -1
GD.Print("Team".Find("I"));// Prints -1GD.Print("Potato".Find("t"));// Prints 2GD.Print("Potato".Find("t",3));// Prints 4GD.Print("Potato".Find("t",5));// Prints -1
Note: If you just want to know whether the string containswhat
, usecontains(). In GDScript, you may also use thein
operator.
intfindn(what:String, from:int = 0)const🔗
Returns the index of thefirstcase-insensitive occurrence ofwhat
in this string, or-1
if there are none. The starting search index can be specified withfrom
, continuing to the end of the string.
Stringformat(values:Variant, placeholder:String = "{_}")const🔗
Formats the string by replacing all occurrences ofplaceholder
with the elements ofvalues
.
values
can be aDictionary, anArray, or anObject. Any underscores inplaceholder
will be replaced with the corresponding keys in advance. Array elements use their index as keys.
# Prints "Waiting for Godot is a play by Samuel Beckett, and Godot Engine is named after it."varuse_array_values="Waiting for {0} is a play by {1}, and {0} Engine is named after it."print(use_array_values.format(["Godot","Samuel Beckett"]))# Prints "User 42 is Godot."print("User {id} is {name}.".format({"id":42,"name":"Godot"}))
Some additional handling is performed whenvalues
is anArray. Ifplaceholder
does not contain an underscore, the elements of thevalues
array will be used to replace one occurrence of the placeholder in order; If an element ofvalues
is another 2-element array, it'll be interpreted as a key-value pair.
# Prints "User 42 is Godot."print("User {} is {}.".format([42,"Godot"],"{}"))print("User {id} is {name}.".format([["id",42],["name","Godot"]]))
When passing anObject, the property names fromObject.get_property_list() are used as keys.
# Prints "Visible true, position (0, 0)"varnode=Node2D.new()print("Visible {visible}, position {position}".format(node))
See also theGDScript format string tutorial.
Note: Each replacement is done sequentially for each element ofvalues
,not all at once. This means that if any element is inserted and it contains another placeholder, it may be changed by the next replacement. While this can be very useful, it often causes unexpected results. If not necessary, make surevalues
's elements do not contain placeholders.
print("{0} {1}".format(["{1}","x"]))# Prints "x x"print("{0} {1}".format(["x","{0}"]))# Prints "x {0}"print("{a} {b}".format({"a":"{b}","b":"c"}))# Prints "c c"print("{a} {b}".format({"b":"c","a":"{b}"}))# Prints "{b} c"
Note: In C#, it's recommended tointerpolate strings with "$", instead.
If the string is a valid file path, returns the base directory name.
vardir_path="/path/to/file.txt".get_base_dir()# dir_path is "/path/to"
If the string is a valid file path, returns the full file path, without the extension.
varbase="/path/to/file.txt".get_basename()# base is "/path/to/file"
If the string is a valid file name or path, returns the file extension without the leading period (.
). Otherwise, returns an empty string.
vara="/path/to/file.txt".get_extension()# a is "txt"varb="cool.txt".get_extension()# b is "txt"varc="cool.font.tres".get_extension()# c is "tres"vard=".pack1".get_extension()# d is "pack1"vare="file.txt.".get_extension()# e is ""varf="file.txt..".get_extension()# f is ""varg="txt".get_extension()# g is ""varh="".get_extension()# h is ""
If the string is a valid file path, returns the file name, including the extension.
varfile="/path/to/icon.png".get_file()# file is "icon.png"
Stringget_slice(delimiter:String, slice:int)const🔗
Splits the string using adelimiter
and returns the substring at indexslice
. Returns the original string ifdelimiter
does not occur in the string. Returns an empty string if theslice
does not exist.
This is faster thansplit(), if you only need one substring.
print("i/am/example/hi".get_slice("/",2))# Prints "example"
intget_slice_count(delimiter:String)const🔗
Returns the total number of slices when the string is split with the givendelimiter
(seesplit()).
Stringget_slicec(delimiter:int, slice:int)const🔗
Splits the string using a Unicode character with codedelimiter
and returns the substring at indexslice
. Returns an empty string if theslice
does not exist.
This is faster thansplit(), if you only need one substring.
Returns the 32-bit hash value representing the string's contents.
Note: Strings with equal hash values arenot guaranteed to be the same, as a result of hash collisions. On the contrary, strings with different hash values are guaranteed to be different.
PackedByteArrayhex_decode()const🔗
Decodes a hexadecimal string as aPackedByteArray.
vartext="hello world"varencoded=text.to_utf8_buffer().hex_encode()# outputs "68656c6c6f20776f726c64"print(buf.hex_decode().get_string_from_utf8())
vartext="hello world";varencoded=text.ToUtf8Buffer().HexEncode();// outputs "68656c6c6f20776f726c64"GD.Print(buf.HexDecode().GetStringFromUtf8());
Converts the string representing a hexadecimal number into anint. The string may be optionally prefixed with"0x"
, and an additional-
prefix for negative numbers.
print("0xff".hex_to_int())# Prints 255print("ab".hex_to_int())# Prints 171
GD.Print("0xff".HexToInt());// Prints 255GD.Print("ab".HexToInt());// Prints 171
Stringhumanize_size(size:int)static🔗
Convertssize
which represents a number of bytes into a human-readable form.
The result is inIEC prefix format, which may end in either"B"
,"KiB"
,"MiB"
,"GiB"
,"TiB"
,"PiB"
, or"EiB"
.
Stringindent(prefix:String)const🔗
Indents every line of the string with the givenprefix
. Empty lines are not indented. See alsodedent() to remove indentation.
For example, the string can be indented with two tabulations using"\t\t"
, or four spaces using" "
.
Stringinsert(position:int, what:String)const🔗
Insertswhat
at the givenposition
in the string.
Returnstrue
if the string is a path to a file or directory, and its starting point is explicitly defined. This method is the opposite ofis_relative_path().
This includes all paths starting with"res://"
,"user://"
,"C:\"
,"/"
, etc.
Returnstrue
if the string's length is0
(""
). See alsolength().
Returnstrue
if the string is a path, and its starting point is dependent on context. The path could begin from the current directory, or the currentNode (if the string is derived from aNodePath), and may sometimes be prefixed with"./"
. This method is the opposite ofis_absolute_path().
boolis_subsequence_of(text:String)const🔗
Returnstrue
if all characters of this string can be found intext
in their original order.
vartext="Wow, incredible!"print("inedible".is_subsequence_of(text))# Prints trueprint("Word!".is_subsequence_of(text))# Prints trueprint("Window".is_subsequence_of(text))# Prints falseprint("".is_subsequence_of(text))# Prints true
boolis_subsequence_ofn(text:String)const🔗
Returnstrue
if all characters of this string can be found intext
in their original order,ignoring case.
boolis_valid_ascii_identifier()const🔗
Returnstrue
if this string is a valid ASCII identifier. A valid ASCII identifier may contain only letters, digits, and underscores (_
), and the first character may not be a digit.
print("node_2d".is_valid_ascii_identifier())# Prints trueprint("TYPE_FLOAT".is_valid_ascii_identifier())# Prints trueprint("1st_method".is_valid_ascii_identifier())# Prints falseprint("MyMethod#2".is_valid_ascii_identifier())# Prints false
See alsois_valid_unicode_identifier().
Returnstrue
if this string does not contain characters that are not allowed in file names (:
/
\
?
*
"
|
%
<
>
).
Returnstrue
if this string represents a valid floating-point number. A valid float may contain only digits, one decimal point (.
), and the exponent letter (e
). It may also be prefixed with a positive (+
) or negative (-
) sign. Any valid integer is also a valid float (seeis_valid_int()). See alsoto_float().
print("1.7".is_valid_float())# Prints trueprint("24".is_valid_float())# Prints trueprint("7e3".is_valid_float())# Prints trueprint("Hello".is_valid_float())# Prints false
boolis_valid_hex_number(with_prefix:bool = false)const🔗
Returnstrue
if this string is a valid hexadecimal number. A valid hexadecimal number only contains digits or lettersA
toF
(either uppercase or lowercase), and may be prefixed with a positive (+
) or negative (-
) sign.
Ifwith_prefix
istrue
, the hexadecimal number needs to prefixed by"0x"
to be considered valid.
print("A08E".is_valid_hex_number())# Prints trueprint("-AbCdEf".is_valid_hex_number())# Prints trueprint("2.5".is_valid_hex_number())# Prints falseprint("0xDEADC0DE".is_valid_hex_number(true))# Prints true
boolis_valid_html_color()const🔗
Returnstrue
if this string is a valid color in hexadecimal HTML notation. The string must be a hexadecimal value (seeis_valid_hex_number()) of either 3, 4, 6 or 8 digits, and may be prefixed by a hash sign (#
). Other HTML notations for colors, such as names orhsl()
, are not considered valid. See alsoColor.html().
boolis_valid_identifier()const🔗
Deprecated: Useis_valid_ascii_identifier() instead.
Returnstrue
if this string is a valid identifier. A valid identifier may contain only letters, digits and underscores (_
), and the first character may not be a digit.
print("node_2d".is_valid_identifier())# Prints trueprint("TYPE_FLOAT".is_valid_identifier())# Prints trueprint("1st_method".is_valid_identifier())# Prints falseprint("MyMethod#2".is_valid_identifier())# Prints false
Returnstrue
if this string represents a valid integer. A valid integer only contains digits, and may be prefixed with a positive (+
) or negative (-
) sign. See alsoto_int().
print("7".is_valid_int())# Prints trueprint("1.65".is_valid_int())# Prints falseprint("Hi".is_valid_int())# Prints falseprint("+3".is_valid_int())# Prints trueprint("-12".is_valid_int())# Prints true
boolis_valid_ip_address()const🔗
Returnstrue
if this string represents a well-formatted IPv4 or IPv6 address. This method considersreserved IP addresses such as"0.0.0.0"
and"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
as valid.
boolis_valid_unicode_identifier()const🔗
Returnstrue
if this string is a valid Unicode identifier.
A valid Unicode identifier must begin with a Unicode character of classXID_Start
or"_"
, and may contain Unicode characters of classXID_Continue
in the other positions.
print("node_2d".is_valid_unicode_identifier())# Prints trueprint("1st_method".is_valid_unicode_identifier())# Prints falseprint("MyMethod#2".is_valid_unicode_identifier())# Prints falseprint("állóképesség".is_valid_unicode_identifier())# Prints trueprint("выносливость".is_valid_unicode_identifier())# Prints trueprint("体力".is_valid_unicode_identifier())# Prints true
See alsois_valid_ascii_identifier().
Note: This method checks identifiers the same way as GDScript. SeeTextServer.is_valid_identifier() for more advanced checks.
Stringjoin(parts:PackedStringArray)const🔗
Returns the concatenation ofparts
' elements, with each element separated by the string calling this method. This method is the opposite ofsplit().
varfruits=["Apple","Orange","Pear","Kiwi"]print(", ".join(fruits))# Prints "Apple, Orange, Pear, Kiwi"print("---".join(fruits))# Prints "Apple---Orange---Pear---Kiwi"
string[]fruits=["Apple","Orange","Pear","Kiwi"];// In C#, this method is static.GD.Print(string.Join(", ",fruits));// Prints "Apple, Orange, Pear, Kiwi"GD.Print(string.Join("---",fruits));// Prints "Apple---Orange---Pear---Kiwi"
Returns a copy of the string with special characters escaped using the JSON standard. Because it closely matches the C standard, it is possible to usec_unescape() to unescape the string, if necessary.
Returns the firstlength
characters from the beginning of the string. Iflength
is negative, strips the lastlength
characters from the string's end.
print("Hello World!".left(3))# Prints "Hel"print("Hello World!".left(-4))# Prints "Hello Wo"
Returns the number of characters in the string. Empty strings (""
) always return0
. See alsois_empty().
Stringlpad(min_length:int, character:String = " ")const🔗
Formats the string to be at leastmin_length
long by addingcharacter
s to the left of the string, if necessary. See alsorpad().
Stringlstrip(chars:String)const🔗
Removes a set of characters defined inchars
from the string's beginning. See alsorstrip().
Note:chars
is not a prefix. Usetrim_prefix() to remove a single prefix, rather than a set of characters.
Does a simple expression match (also called "glob" or "globbing"), where*
matches zero or more arbitrary characters and?
matches any single character except a period (.
). An empty string or empty expression always evaluates tofalse
.
Does a simplecase-insensitive expression match, where*
matches zero or more arbitrary characters and?
matches any single character except a period (.
). An empty string or empty expression always evaluates tofalse
.
PackedByteArraymd5_buffer()const🔗
Returns theMD5 hash of the string as aPackedByteArray.
Returns theMD5 hash of the string as anotherString.
intnaturalcasecmp_to(to:String)const🔗
Performs acase-sensitive,natural order comparison to another string. Returns-1
if less than,1
if greater than, or0
if equal. "Less than" or "greater than" are determined by theUnicode code points of each string, which roughly matches the alphabetical order.
When used for sorting, natural order comparison orders sequences of numbers by the combined value of each digit as is often expected, instead of the single digit's value. A sorted sequence of numbered strings will be["1","2","3",...]
, not["1","10","2","3",...]
.
With different string lengths, returns1
if this string is longer than theto
string, or-1
if shorter. Note that the length of empty strings isalways0
.
To get abool result from a string comparison, use the==
operator instead. See alsonaturalnocasecmp_to(),filecasecmp_to(), andnocasecmp_to().
intnaturalnocasecmp_to(to:String)const🔗
Performs acase-insensitive,natural order comparison to another string. Returns-1
if less than,1
if greater than, or0
if equal. "Less than" or "greater than" are determined by theUnicode code points of each string, which roughly matches the alphabetical order. Internally, lowercase characters are converted to uppercase for the comparison.
When used for sorting, natural order comparison orders sequences of numbers by the combined value of each digit as is often expected, instead of the single digit's value. A sorted sequence of numbered strings will be["1","2","3",...]
, not["1","10","2","3",...]
.
With different string lengths, returns1
if this string is longer than theto
string, or-1
if shorter. Note that the length of empty strings isalways0
.
To get abool result from a string comparison, use the==
operator instead. See alsonaturalcasecmp_to(),filenocasecmp_to(), andcasecmp_to().
intnocasecmp_to(to:String)const🔗
Performs acase-insensitive comparison to another string. Returns-1
if less than,1
if greater than, or0
if equal. "Less than" or "greater than" are determined by theUnicode code points of each string, which roughly matches the alphabetical order. Internally, lowercase characters are converted to uppercase for the comparison.
With different string lengths, returns1
if this string is longer than theto
string, or-1
if shorter. Note that the length of empty strings isalways0
.
To get abool result from a string comparison, use the==
operator instead. See alsocasecmp_to(),filenocasecmp_to(), andnaturalnocasecmp_to().
Stringnum(number:float, decimals:int = -1)static🔗
Converts afloat to a string representation of a decimal number, with the number of decimal places specified indecimals
.
Ifdecimals
is-1
as by default, the string representation may only have up to 14 significant digits, with digits before the decimal point having priority over digits after.
Trailing zeros are not included in the string. The last digit is rounded, not truncated.
String.num(3.141593)# Returns "3.141593"String.num(3.141593,3)# Returns "3.142"String.num(3.14159300)# Returns "3.141593"# Here, the last digit will be rounded up,# which reduces the total digit count, since trailing zeros are removed:String.num(42.129999,5)# Returns "42.13"# If `decimals` is not specified, the maximum number of significant digits is 14:String.num(-0.0000012345432123454321)# Returns "-0.00000123454321"String.num(-10000.0000012345432123454321)# Returns "-10000.0000012345"
Stringnum_int64(number:int, base:int = 10, capitalize_hex:bool = false)static🔗
Converts the givennumber
to a string representation, with the givenbase
.
By default,base
is set to decimal (10
). Other common bases in programming include binary (2
),octal (8
), hexadecimal (16
).
Ifcapitalize_hex
istrue
, digits higher than 9 are represented in uppercase.
Stringnum_scientific(number:float)static🔗
Converts the givennumber
to a string representation, in scientific notation.
varn=-5.2e8print(n)# Prints -520000000print(String.num_scientific(n))# Prints -5.2e+08
// This method is not implemented in C#.// Use `string.ToString()` with "e" to achieve similar results.varn=-5.2e8f;GD.Print(n);// Prints -520000000GD.Print(n.ToString("e1"));// Prints -5.2e+008
Note: In C#, this method is not implemented. To achieve similar results, see C#'sStandard numeric format strings
Stringnum_uint64(number:int, base:int = 10, capitalize_hex:bool = false)static🔗
Converts the given unsignedint to a string representation, with the givenbase
.
By default,base
is set to decimal (10
). Other common bases in programming include binary (2
),octal (8
), hexadecimal (16
).
Ifcapitalize_hex
istrue
, digits higher than 9 are represented in uppercase.
Stringpad_decimals(digits:int)const🔗
Formats the string representing a number to have an exact number ofdigits
after the decimal point.
Stringpad_zeros(digits:int)const🔗
Formats the string representing a number to have an exact number ofdigits
before the decimal point.
Stringpath_join(file:String)const🔗
Concatenatesfile
at the end of the string as a subpath, adding/
if necessary.
Example:"this/is".path_join("path")=="this/is/path"
.
Repeats this string a number of times.count
needs to be greater than0
. Otherwise, returns an empty string.
Stringreplace(what:String, forwhat:String)const🔗
Replaces all occurrences ofwhat
inside the string with the givenforwhat
.
Stringreplacen(what:String, forwhat:String)const🔗
Replaces allcase-insensitive occurrences ofwhat
inside the string with the givenforwhat
.
Returns the copy of this string in reverse order. This operation works on unicode codepoints, rather than sequences of codepoints, and may break things like compound letters or emojis.
intrfind(what:String, from:int = -1)const🔗
Returns the index of thelast occurrence ofwhat
in this string, or-1
if there are none. The search's start can be specified withfrom
, continuing to the beginning of the string. This method is the reverse offind().
intrfindn(what:String, from:int = -1)const🔗
Returns the index of thelastcase-insensitive occurrence ofwhat
in this string, or-1
if there are none. The starting search index can be specified withfrom
, continuing to the beginning of the string. This method is the reverse offindn().
Returns the lastlength
characters from the end of the string. Iflength
is negative, strips the firstlength
characters from the string's beginning.
print("Hello World!".right(3))# Prints "ld!"print("Hello World!".right(-4))# Prints "o World!"
Stringrpad(min_length:int, character:String = " ")const🔗
Formats the string to be at leastmin_length
long, by addingcharacter
s to the right of the string, if necessary. See alsolpad().
PackedStringArrayrsplit(delimiter:String = "", allow_empty:bool = true, maxsplit:int = 0)const🔗
Splits the string using adelimiter
and returns an array of the substrings, starting from the end of the string. The splits in the returned array appear in the same order as the original string. Ifdelimiter
is an empty string, each substring will be a single character.
Ifallow_empty
isfalse
, empty strings between adjacent delimiters are excluded from the array.
Ifmaxsplit
is greater than0
, the number of splits may not exceedmaxsplit
. By default, the entire string is split, which is mostly identical tosplit().
varsome_string="One,Two,Three,Four"varsome_array=some_string.rsplit(",",true,1)print(some_array.size())# Prints 2print(some_array[0])# Prints "One,Two,Three"print(some_array[1])# Prints "Four"
// In C#, there is no String.RSplit() method.
Stringrstrip(chars:String)const🔗
Removes a set of characters defined inchars
from the string's end. See alsolstrip().
Note:chars
is not a suffix. Usetrim_suffix() to remove a single suffix, rather than a set of characters.
PackedByteArraysha1_buffer()const🔗
Returns theSHA-1 hash of the string as aPackedByteArray.
Returns theSHA-1 hash of the string as anotherString.
PackedByteArraysha256_buffer()const🔗
Returns theSHA-256 hash of the string as aPackedByteArray.
Returns theSHA-256 hash of the string as anotherString.
floatsimilarity(text:String)const🔗
Returns the similarity index (Sørensen-Dice coefficient) of this string compared to another. A result of1.0
means totally similar, while0.0
means totally dissimilar.
print("ABC123".similarity("ABC123"))# Prints 1.0print("ABC123".similarity("XYZ456"))# Prints 0.0print("ABC123".similarity("123ABC"))# Prints 0.8print("ABC123".similarity("abc123"))# Prints 0.4
If the string is a valid file path, converts the string into a canonical path. This is the shortest possible path, without"./"
, and all the unnecessary".."
and"/"
.
varsimple_path="./path/to///../file".simplify_path()print(simple_path)# Prints "path/file"
PackedStringArraysplit(delimiter:String = "", allow_empty:bool = true, maxsplit:int = 0)const🔗
Splits the string using adelimiter
and returns an array of the substrings. Ifdelimiter
is an empty string, each substring will be a single character. This method is the opposite ofjoin().
Ifallow_empty
isfalse
, empty strings between adjacent delimiters are excluded from the array.
Ifmaxsplit
is greater than0
, the number of splits may not exceedmaxsplit
. By default, the entire string is split.
varsome_array="One,Two,Three,Four".split(",",true,2)print(some_array.size())# Prints 3print(some_array[0])# Prints "One"print(some_array[1])# Prints "Two"print(some_array[2])# Prints "Three,Four"
// C#'s `Split()` does not support the `maxsplit` parameter.varsomeArray="One,Two,Three".Split(",");GD.Print(someArray[0]);// Prints "One"GD.Print(someArray[1]);// Prints "Two"GD.Print(someArray[2]);// Prints "Three"
Note: If you only need one substring from the array, consider usingget_slice() which is faster. If you need to split strings with more complex rules, use theRegEx class instead.
PackedFloat64Arraysplit_floats(delimiter:String, allow_empty:bool = true)const🔗
Splits the string into floats by using adelimiter
and returns aPackedFloat64Array.
Ifallow_empty
isfalse
, empty or invalidfloat conversions between adjacent delimiters are excluded.
vara="1,2,4.5".split_floats(",")# a is [1.0, 2.0, 4.5]varc="1| ||4.5".split_floats("|")# c is [1.0, 0.0, 0.0, 4.5]varb="1| ||4.5".split_floats("|",false)# b is [1.0, 4.5]
Stringstrip_edges(left:bool = true, right:bool = true)const🔗
Strips all non-printable characters from the beginning and the end of the string. These include spaces, tabulations (\t
), and newlines (\n
\r
).
Ifleft
isfalse
, ignores the string's beginning. Likewise, ifright
isfalse
, ignores the string's end.
Strips all escape characters from the string. These include all non-printable control characters of the first page of the ASCII table (values from 0 to 31), such as tabulation (\t
) and newline (\n
,\r
) characters, butnot spaces.
Stringsubstr(from:int, len:int = -1)const🔗
Returns part of the string from the positionfrom
with lengthlen
. Iflen
is-1
(as by default), returns the rest of the string starting from the given position.
PackedByteArrayto_ascii_buffer()const🔗
Converts the string to anASCII/Latin-1 encodedPackedByteArray. This method is slightly faster thanto_utf8_buffer(), but replaces all unsupported characters with spaces. This is the inverse ofPackedByteArray.get_string_from_ascii().
Returns the string converted tocamelCase
.
Converts the string representing a decimal number into afloat. This method stops on the first non-number character, except the first decimal point (.
) and the exponent letter (e
). See alsois_valid_float().
vara="12.35".to_float()# a is 12.35varb="1.2.3".to_float()# b is 1.2varc="12xy3".to_float()# c is 12.0vard="1e3".to_float()# d is 1000.0vare="Hello!".to_float()# e is 0.0
Converts the string representing an integer number into anint. This method removes any non-number character and stops at the first decimal point (.
). See alsois_valid_int().
vara="123".to_int()# a is 123varb="x1y2z3".to_int()# b is 123varc="-1.2.3".to_int()# c is -1vard="Hello!".to_int()# d is 0
Returns the string converted tolowercase
.
Returns the string converted toPascalCase
.
Returns the string converted tosnake_case
.
Note: Numbers followed by asingle letter are not separated in the conversion to keep some words (such as "2D") together.
"Node2D".to_snake_case()# Returns "node_2d""2nd place".to_snake_case()# Returns "2_nd_place""Texture3DAssetFolder".to_snake_case()# Returns "texture_3d_asset_folder"
"Node2D".ToSnakeCase();// Returns "node_2d""2nd place".ToSnakeCase();// Returns "2_nd_place""Texture3DAssetFolder".ToSnakeCase();// Returns "texture_3d_asset_folder"
Returns the string converted toUPPERCASE
.
PackedByteArrayto_utf8_buffer()const🔗
Converts the string to aUTF-8 encodedPackedByteArray. This method is slightly slower thanto_ascii_buffer(), but supports all UTF-8 characters. For most cases, prefer using this method. This is the inverse ofPackedByteArray.get_string_from_utf8().
PackedByteArrayto_utf16_buffer()const🔗
Converts the string to aUTF-16 encodedPackedByteArray. This is the inverse ofPackedByteArray.get_string_from_utf16().
PackedByteArrayto_utf32_buffer()const🔗
Converts the string to aUTF-32 encodedPackedByteArray. This is the inverse ofPackedByteArray.get_string_from_utf32().
PackedByteArrayto_wchar_buffer()const🔗
Converts the string to awide character (wchar_t
, UTF-16 on Windows, UTF-32 on other platforms) encodedPackedByteArray. This is the inverse ofPackedByteArray.get_string_from_wchar().
Stringtrim_prefix(prefix:String)const🔗
Removes the givenprefix
from the start of the string, or returns the string unchanged.
Stringtrim_suffix(suffix:String)const🔗
Removes the givensuffix
from the end of the string, or returns the string unchanged.
Returns the character code at positionat
.
Decodes the string from its URL-encoded format. This method is meant to properly decode the parameters in a URL when receiving an HTTP request. See alsouri_encode().
varurl="$DOCS_URL/?highlight=Godot%20Engine%3%docs"print(url.uri_decode())# Prints "$DOCS_URL/?highlight=Godot Engine:docs"
varurl="$DOCS_URL/?highlight=Godot%20Engine%3%docs"GD.Print(url.URIDecode())// Prints "$DOCS_URL/?highlight=Godot Engine:docs"
Encodes the string to URL-friendly format. This method is meant to properly encode the parameters in a URL when sending an HTTP request. See alsouri_decode().
varprefix="$DOCS_URL/?highlight="varurl=prefix+"Godot Engine:docs".uri_encode()print(url)# Prints "$DOCS_URL/?highlight=Godot%20Engine%3%docs"
varprefix="$DOCS_URL/?highlight=";varurl=prefix+"Godot Engine:docs".URIEncode();GD.Print(url);// Prints "$DOCS_URL/?highlight=Godot%20Engine%3%docs"
Stringvalidate_filename()const🔗
Returns a copy of the string with all characters that are not allowed inis_valid_filename() replaced with underscores.
Stringvalidate_node_name()const🔗
Returns a copy of the string with all characters that are not allowed inNode.name (.
:
@
/
"
%
) replaced with underscores.
Stringxml_escape(escape_quotes:bool = false)const🔗
Returns a copy of the string with special characters escaped using the XML standard. Ifescape_quotes
istrue
, the single quote ('
) and double quote ("
) characters are also escaped.
Returns a copy of the string with escaped characters replaced by their meanings according to the XML standard.
Operator Descriptions
booloperator !=(right:String)🔗
Returnstrue
if both strings do not contain the same sequence of characters.
booloperator !=(right:StringName)🔗
Returnstrue
if thisString is not equivalent to the givenStringName.
Stringoperator %(right:Variant)🔗
Formats theString, replacing the placeholders with one or more parameters. To pass multiple parameters,right
needs to be anArray.
print("I caught%d fishes!"%2)# Prints "I caught 2 fishes!"varmy_message="Travelling to%s, at%2.2f km/h."varlocation="Deep Valley"varspeed=40.3485print(my_message%[location,speed])# Prints "Travelling to Deep Valley, at 40.35 km/h."
For more information, see theGDScript format strings tutorial.
Note: In C#, this operator is not available. Instead, seehow to interpolate strings with "$".
Stringoperator +(right:String)🔗
Appendsright
at the end of thisString, also known as a string concatenation.
Stringoperator +(right:StringName)🔗
Appendsright
at the end of thisString, returning aString. This is also known as a string concatenation.
Returnstrue
if the leftString comes beforeright
inUnicode order, which roughly matches the alphabetical order. Useful for sorting.
booloperator <=(right:String)🔗
Returnstrue
if the leftString comes beforeright
inUnicode order, which roughly matches the alphabetical order, or if both are equal.
booloperator ==(right:String)🔗
Returnstrue
if both strings contain the same sequence of characters.
booloperator ==(right:StringName)🔗
Returnstrue
if thisString is equivalent to the givenStringName.
Returnstrue
if the leftString comes afterright
inUnicode order, which roughly matches the alphabetical order. Useful for sorting.
booloperator >=(right:String)🔗
Returnstrue
if the leftString comes afterright
inUnicode order, which roughly matches the alphabetical order, or if both are equal.
Returns a newString that only contains the character atindex
. Indices start from0
. Ifindex
is greater or equal to0
, the character is fetched starting from the beginning of the string. Ifindex
is a negative value, it is fetched starting from the end. Accessing a string out-of-bounds will cause a run-time error, pausing the project execution if run from the editor.