Menu
CoddyTech

String Methods

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 1 of 78.

You already know three string methods: length(), to_upper() and to_lower(). Strings have many more. None of them changes the string it is called on: each one returns a new string, so print the result or store it.

var title := "game"
title.to_upper()
print(title)
title = title.to_upper()
print(title)
game
GAME

capitalize() writes every word with an uppercase first letter and the rest in lowercase. It also turns underscores into spaces, so it can turn a variable-style name into a label:

print("the legend of zelda".capitalize())
print("max_hp".capitalize())
The Legend Of Zelda
Max Hp

reverse() returns the characters in the opposite order, left(n) the first n characters and right(n) the last n:

var hero := "Godot"
print(hero.reverse())
print(hero.left(3))
print(hero.right(2))
todoG
God
ot

The padding methods add characters until the string reaches a given length. pad_zeros(n) puts zeros in front of a number written as text, lpad(n, c) adds the character c on the left and rpad(n, c) on the right (spaces when you leave c out):

print("42".pad_zeros(5))
print("7".lpad(3, "*"))
print("Ana".rpad(6, ".") + "10")
00042
**7
Ana...10

is_empty() returns true when a string has no characters at all: "".is_empty() is true.

challenge icon

Challenge

Easy

The program reads a player name written in lowercase with underscores between the words, such as shadow_fox, and a score. Both are already stored as strings in player_name and score.

Print four lines:

  1. The name with capitalize()
  2. The name reversed
  3. The first 3 characters of the name, in uppercase
  4. The score padded with zeros to 6 digits

For the inputs shadow_fox and 420, the output is:

Shadow Fox
xof_wodahs
SHA
000420

Try it yourself

extends Node

func _ready():
	var player_name := OS.read_string_from_stdin()
	var score := OS.read_string_from_stdin()
	# Print the four lines
quiz iconTest yourself

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

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler