String Methods
Use split(), strip(), replace(), lower(), and startswith() to transform strings
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
String methods
Python strings have built-in methods for transforming text. Methods do not change the original string — they return a new one.
| Method | What it does |
|---|---|
.strip() | Remove leading and trailing whitespace |
.split() | Split into a list of words (default: whitespace) |
.lower() | Convert to lowercase |
.replace(old, new) | Replace all occurrences of old with new |
.startswith(prefix) | Return True if the string starts with prefix |
Chaining methods
You can call methods one after another on the same string.
text = " Hello, World! "
result = text.strip().lower()
print(result) # hello, world!
Instructions
Apply five string methods to a text value.
- Assign
" Python is fun! "totext. - Assign
text.strip()toclean. Callprint(clean). - Assign
clean.split()towords. Callprint(words). - Assign
clean.lower()tolower. Callprint(lower). - Assign
clean.replace("fun", "great")toreplaced. Callprint(replaced). - Call
print(clean.startswith("Python")).
# Step 1: Assign text # Step 2: Strip whitespace into clean and print # Step 3: Split clean into words and print # Step 4: Lowercase clean into lower and print # Step 5: Replace "fun" with "great" into replaced and print # Step 6: Print whether clean starts with "Python"
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding