Replace and Trim
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 3 of 78.
replace(what, with) returns a new string where every appearance of what is replaced with with. Replacing with an empty string removes the text:
var phone := "555-123-4567"
print(phone.replace("-", ""))
print(phone.replace("-", " "))
print(phone)5551234567
555 123 4567
555-123-4567The original string does not change. replace() is case-sensitive; replacen() does the same job and ignores case:
var chat := "Hello hello HELLO"
print(chat.replace("hello", "hi"))
print(chat.replacen("hello", "hi"))Hello hi HELLO
hi hi hiText typed by a user often has extra spaces around it. strip_edges() removes spaces, tabs and line breaks from both ends and keeps the ones in the middle:
var typed := " Ana Lee "
print("[" + typed.strip_edges() + "]")[Ana Lee]strip_edges(true, false) trims only the left end and strip_edges(false, true) only the right end. To remove one specific text at an end, use trim_prefix() or trim_suffix(). They change nothing when the text is not there:
print("level_03.tscn".trim_suffix(".tscn"))
print("level_03.tscn".trim_suffix(".png"))level_03
level_03.tscnEach of these methods returns a string, so you can chain them: raw.strip_edges().to_lower().replace(" ", "_").
Challenge
EasyThe program reads a level title into title. Turn it into a slug, a version of the title that can be used as a file name, and print it. In this order:
- Remove the spaces at both ends
- Convert it to lowercase
- Replace every remaining space with
- - Remove every
!,?and.
For the input Is Godot Fun? (with spaces around it), the output is:
is-godot-funTry it yourself
extends Node
func _ready():
var title := OS.read_string_from_stdin()
# Build the slug and print it
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