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
GAMEcapitalize() 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 Hpreverse() 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
otThe 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...10is_empty() returns true when a string has no characters at all: "".is_empty() is true.
Challenge
EasyThe 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:
- The name with
capitalize() - The name reversed
- The first 3 characters of the name, in uppercase
- The score padded with zeros to 6 digits
For the inputs shadow_fox and 420, the output is:
Shadow Fox
xof_wodahs
SHA
000420Try 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler