Lesson 1 · Unit 05
Strings
Methods that cut, clean and rebuild text
What you practise
- Strings never change in place,
split,join,strip,replace,find,startswith, slicing, formatting numbers inside f-strings
Try a question from this lesson
Pick one
upper() gives back the text in capital letters. Look closely at what line 2 does with that result. What does this program show?
name = "ada"
name.upper()
print(name)Hint
Line 2 makes a value. Does any name end up holding it?
Correct answer
ada
Why
Line 2 makes a new string "ADA" and then throws it away, because nothing keeps it. name still holds "ada". A string never changes in place: to keep the result, give it a name.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Strings never change
upper() is a method, like append on a list: a function that belongs to a value, called with a dot.
A string method never changes the string it is called on. It gives back a new string. Keep that new string with a name, or it is lost.
name = "ada"
shout = name.upper()
print(name) # ada
print(shout) # ADA
name = name.upper() # keep it as name
print(name) # ADAConcept
split and join
split cuts a string into a list of pieces. You say where to cut. With nothing in the brackets, it cuts at spaces.
join does the opposite: it glues a list of strings into one string. The string before the dot goes between the pieces.
line = "red,green,blue"
parts = line.split(",")
print(parts)
# ['red', 'green', 'blue']
print("-".join(parts))
# red-green-blue10 more exercises in the app
- 4× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.