String Formatting
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 33 of 92.
Joining many values with + and str() makes long lines. A format string is easier to read: you write the text once, put a placeholder where each value goes, and give the values after the % operator:
var player_name := "Ada"
var age := 12
print("%s is %d years old" % [player_name, age])This prints Ada is 12 years old. The values go inside square brackets, in the same order as the placeholders. With one value, the brackets can be left out: "HP: %d" % 80 is HP: 80.
The placeholders you will use most:
%sinserts any value as text%dinserts a whole number%.2finserts a decimal number rounded to 2 decimal places
For example, with var price := 2.5:
print("Price: %.2f" % price)
print("Price: %s" % price)The first line prints Price: 2.50, the second prints Price: 2.5.
To print a percent sign in a format string, write %%: "%d%%" % 50 is 50%.
The number of values must match the number of placeholders. When a value is missing, GDScript reports a formatting error as the line runs.
Challenge
EasyA shop sells potions. The program stores the item name, its price and the quantity bought. Use one format string with the % operator to print the receipt line:
Item: Health Potion x3, total: $7.50The total is price * quantity, shown with 2 decimal places. Put the values in square brackets after %.
Try it yourself
extends Node
func _ready():
var item_name := "Health Potion"
var price := 2.5
var quantity := 3
# Print the receipt line with a format string
pass
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler