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.

MethodWhat 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.

  1. Assign " Python is fun! " to text.
  2. Assign text.strip() to clean. Call print(clean).
  3. Assign clean.split() to words. Call print(words).
  4. Assign clean.lower() to lower. Call print(lower).
  5. Assign clean.replace("fun", "great") to replaced. Call print(replaced).
  6. Call print(clean.startswith("Python")).

Next Chapter →