Python lesson 16

String Methods

Clean, search, and reshape text using Python's built-in string tools!

Strings Have Built-In Superpowers

Python strings come with methods. Functions you call with a dot. The ones you will use here are: .strip() removes leading and trailing spaces. .replace(old, new) swaps one piece of text for another. .split() breaks a string into a list of words. .join(list) glues a list of strings back together. .lower() makes every letter small. .capitalize() makes the first letter a capital and the rest small.

" hello ".strip() # "hello"
"a,b,c".split(",") # ["a", "b", "c"]
",".join(["a","b","c"]) # "a,b,c"

print("  hello  ".strip())
print("a,b,c".split(","))
print(",".join(["a", "b", "c"]))

Cleaning Up Text

messy = "  hello world  "
print(messy.strip())
print(messy.strip().replace("world", "there"))

Cleaning a String

Click Run to see strip(), lower(), and replace() working together on a messy piece of text.

Hint: Click Run! Notice that each method returns a new string. The original text variable is never changed.

text = "  Hello, World!  "
clean = text.strip()
print(clean)
print(clean.lower())
print(clean.replace("World", "Python"))

Word Counter

Split a sentence into a list of words and count them. Then modify the sentence and run again to see the count update.

Hint: .split() with no argument splits on any whitespace. Len() counts the items in the resulting list. Try adding or removing words from the sentence.

sentence = "Python is fun and easy to learn"
words = sentence.split()
print("Word count:", len(words))
print("Words:", words)

Input Cleaner

Raw text from a user often has extra spaces and inconsistent casing. Clean it up with strip(), lower(), split(), and join(). Run and then try a different name!

Hint: Each method handles one job: strip removes spaces, lower makes it lowercase, split divides it, capitalize fixes each word. Try raw = " BOB JONES ".

raw = "  ALICE SMITH  "
stripped = raw.strip()
lower = stripped.lower()
words = lower.split()
formatted = words[0].capitalize() + " " + words[1].capitalize()
print("Cleaned:", formatted)

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.