Menu
CoddyTech

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:

  • %s inserts any value as text
  • %d inserts a whole number
  • %.2f inserts 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 icon

Challenge

Easy

A 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.50

The 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online GDScript compiler