Skip to main content

Unit 5 · Gotta Catch 'Em All! · Lesson 43 of 57

String Theory

String theory

Strings come with a bunch of built-in tools called methods. You use them with a . after the string, like .append() on a list:

MethodWhat it doesExampleResult
.upper()ALL CAPS"amer".upper()"AMER"
.lower()all lowercase"KaRl".lower()"karl"
.strip()removes spaces from both ends" zain ".strip()"zain"
.replace(a, b)swaps every a for b"amer123".replace("123", "!")"amer!"
.split()chops it into a list of words"Alex did it".split()["Alex", "did", "it"]

Let's try one. Before you run this, what do you think the last line prints?

Run it!

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Question

Answer it in the lesson and it is checked as soon as you send it. Create a free account to do this part.

Methods return a new string

.upper() doesn't change the string. It returns a brand new, all caps copy of it, and leaves the original alone.

So name.upper() on its own line is just like add(2, 3) back in Returning Ruckus. The new string gets teleported back, nobody stores it, and it disappears.

If you want to keep it, store it:

name = "amer"
name = name.upper()
print(name)
AMER

Strings in Python can never be changed. Every string method gives you back a new one instead. (Lists are different: .append() really does change the list. Python's fun like that.)

Chaining

Since every method gives back a new string, you can stick them right after each other:

username = "   KaRL  "
print(username.strip().lower())
karl

.strip() gives back "KaRL", then .lower() runs on that, and gives back "karl".

This is super useful for logins. People type their usernames in all kinds of ways, and you want Karl, KARL and karl to all count as the same person.

Make a function called clean_username that takes a username and returns it with the spaces stripped off the ends, and in all lowercase.

clean_username("  ZaIn ")   # "zain"

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Do this lesson for real

With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.