GDScript format strings
Godot offers multiple ways to dynamically change the contents of strings:
Format strings:
varstring="Ihave%scats."%"3"The
String.format()method:varstring="Ihave{0}cats.".format([3])String concatenation:
varstring="Ihave"+str(3)+"cats."
This page explains how to use format strings, and briefly explains theformat()method and string concatenation.
Format strings
Format strings are a way to reuse text templates to succinctly create differentbut similar strings.
Format strings are just like normal strings, except they contain certainplaceholder character sequences such as%s. These placeholders can thenbe replaced by parameters handed to the format string.
Examine this concrete GDScript example:
# Define a format string with placeholder '%s'varformat_string="We're waiting for%s."# Using the '%' operator, the placeholder is replaced with the desired valuevaractual_string=format_string%"Godot"print(actual_string)# Output: "We're waiting for Godot."
Placeholders always start with a%, but the next character or characters,theformat specifier, determines how the given value is converted to astring.
The%s seen in the example above is the simplest placeholder and works formost use cases: it converts the value by the same method by which an implicitString conversion orstr() would convertit. Strings remain unchanged, booleans turn into either"True" or"False",anint orfloat becomes a decimal, and other types usually return their datain a human-readable string.
There are otherformat specifiers.
Multiple placeholders
Format strings may contain multiple placeholders. In such a case, the valuesare handed in the form of an array, one value per placeholder (unless using aformat specifier with*, seedynamic padding):
varformat_string="%s was reluctant to learn%s, but now he enjoys it."varactual_string=format_string%["Estragon","GDScript"]print(actual_string)# Output: "Estragon was reluctant to learn GDScript, but now he enjoys it."
Note the values are inserted in order. Remember all placeholders must bereplaced at once, so there must be an appropriate number of values.
Format specifiers
There are format specifiers other thans that can be used in placeholders.They consist of one or more characters. Some of them work by themselves likes, some appear before other characters, some only work with certainvalues or characters.
Placeholder types
One and only one of these must always appear as the last character in a formatspecifier. Apart froms, these require certain types of parameters.
| Simple conversion to String by the same method as implicitString conversion. |
| A singleUnicode character. Accepts a Unicode code point(integer) or a single-character string. Supports values beyond 255. |
| Adecimal integer. Expects an integer or a real number(will be floored). |
| Anoctal integer. Expects an integer or a real number(will be floored). |
| Ahexadecimal integer withlower-case letters.Expects an integer or a real number (will be floored). |
| Ahexadecimal integer withupper-case letters.Expects an integer or a real number (will be floored). |
| Adecimal real number. Expects an integer or a real number. |
| Avector. Expects any float or int-based vector object ( |
Placeholder modifiers
These characters appear before the above. Some of them work only under certainconditions.
| In number specifiers,show + sign if positive. |
Integer | Setpadding. Padded with spaces or with zeroes if integerstarts with |
| Before |
| Pad to the right rather than the left. |
| Dynamic padding, expects additional integer parameter to setpadding or precision after |
Padding
The. (dot),* (asterisk),- (minus sign) and digit(0-9) characters are used for padding. This allows printing severalvalues aligned vertically as if in a column, provided a fixed-width font isused.
To pad a string to a minimum length, add an integer to the specifier:
print("%10d"%12345)# output: " 12345"# 5 leading spaces for a total length of 10
If the integer starts with0, integer values are padded with zeroesinstead of white space:
print("%010d"%12345)# output: "0000012345"
Precision can be specified for real numbers by adding a. (dot) with aninteger following it. With no integer after., a precision of 0 is used,rounding to integer values. The integer to use for padding must appear beforethe dot.
# Pad to minimum length of 10, round to 3 decimal placesprint("%10.3f"%10000.5555)# Output: " 10000.556"# 1 leading space
The- character will cause padding to the right rather than the left,useful for right text alignment:
print("%-10d"%12345678)# Output: "12345678 "# 2 trailing spaces
Dynamic padding
By using the* (asterisk) character, the padding or precision can be setwithout modifying the format string. It is used in place of an integer in theformat specifier. The values for padding and precision are then passed whenformatting:
varformat_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
It is still possible to pad with zeroes in integer placeholders by adding0before*:
print("%0*d"%[2,3])# Output: "03"
Escape sequence
To insert a literal% character into a format string, it must be escaped toavoid reading it as a placeholder. This is done by doubling the character:
varhealth=56print("Remaining health:%d%%"%health)# Output: "Remaining health: 56%"
String format method
There is also another way to format text in GDScript, namely theString.format()method. It replaces all occurrences of a key in the string with the correspondingvalue. The method can handle arrays or dictionaries for the key/value pairs.
Arrays can be used as key, index, or mixed style (see below examples). Order onlymatters when the index or mixed style of Array is used.
A quick example in GDScript:
# Define a format stringvarformat_string="We're waiting for {str}"# Using the 'format' method, replace the 'str' placeholdervaractual_string=format_string.format({"str":"Godot"})print(actual_string)# Output: "We're waiting for Godot"
Format method examples
The following are some examples of how to use the various invocations of theString.format() method.
Type | Style | Example | Result |
Dictionary | key |
| Hi, Godette v3.0! |
Dictionary | index |
| Hi, Godette v3.0! |
Dictionary | mix |
| Hi, Godette v3.0! |
Array | key |
| Hi, Godette v3.0! |
Array | index |
| Hi, Godette v3.0! |
Array | mix |
| Hi, Godette v3.0! |
Array | no index |
| Hi, Godette v3.0! |
Placeholders can also be customized when usingString.format, here's someexamples of that functionality.
Type | Example | Result |
Infix (default) |
| Hi, Godette v3.0 |
Postfix |
| Hi, Godette v3.0 |
Prefix |
| Hi, Godette v3.0 |
Combining both theString.format method and the% operator could be useful, asString.format does not have a way to manipulate the representation of numbers.
Example | Result |
| Hi, Godette v3.11 |
String concatenation
You can also combine strings byconcatenating them together, using the+operator.
# Define a base stringvarbase_string="We're waiting for "# Concatenate the stringvaractual_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 usingthestr() function. There is no way to specify the string format of convertedvalues.
varname_string="Godette"varversion=3.0varactual_string="Hi, "+name_string+" v"+str(version)+"!"print(actual_string)# Output: "Hi, Godette v3!"
Because of these limitations, format strings or theformat() method are oftena better choice. In many cases, string concatenation is also less readable.
Note
In Godot's C++ code, GDScript format strings can be accessed using thevformat() helper function in theVariant header.