Lesson 11 of 18 · 3 min
String Methods — Built-in Text Tools
A method is a function that belongs to a specific type. Call it with a dot: variable.method_name()
Case-Changing Methods
text = "hello world python" # all lowercase text to start print(text.upper()) # convert ALL characters to UPPERCASE print(text.lower()) # convert all characters to lowercase print(text.title()) # Capitalize The First Letter Of Each Word print(text.capitalize()) # Capitalize only the very first letter
Output: HELLO WORLD PYTHON hello world python Hello World Python Hello world python
Whitespace Removal Methods
messy = " Hello, World! " # extra spaces on both sides print(messy.strip()) # remove spaces from BOTH left and right ends print(messy.lstrip()) # remove spaces from LEFT end only print(messy.rstrip()) # remove spaces from RIGHT end only
Output: Hello, World! Hello, World! Hello, World!
Searching and Replacing
sentence = "The cat sat on the mat" # text to work with
print(sentence.count("at")) # count how many times "at" appears in text
print(sentence.find("sat")) # find start index of "sat" (-1 if not found)
print(sentence.replace("cat", "dog")) # replace every "cat" with "dog"
print(sentence.startswith("The")) # does the string START with "The"?
print(sentence.endswith("mat")) # does the string END with "mat"?
print("cat" in sentence) # is "cat" ANYWHERE in the string?
Output: 3 8 The dog sat on the mat True True True
Split and Join
csv_data = "Ahmed,21,Chennai,3.75" # data separated by commas
parts = csv_data.split(",") # break into a list at every comma
print(parts) # display the list of separate pieces
print(parts[0]) # access just the name (index 0)
print(parts[2]) # access just the city (index 2)
words = ["Python", "is", "awesome"] # a list of words
sentence = " ".join(words) # join them with a space between each word
print(sentence) # display the joined result
Output: ['Ahmed', '21', 'Chennai', '3.75'] Ahmed Chennai Python is awesome
Quick Reference — All Major String Methods
| Method | What It Does | Example Output |
|---|---|---|
.upper() | ALL UPPERCASE | "hi".upper() → "HI" |
.lower() | all lowercase | "HI".lower() → "hi" |
.title() | Title Case | "hello world".title() → "Hello World" |
.strip() | Remove edge spaces | " hi ".strip() → "hi" |
.replace(old, new) | Swap text | "cat".replace("c","b") → "bat" |
.split(sep) | Break into list | "a,b".split(",") → ["a","b"] |
.count(sub) | Count occurrences | "aaa".count("a") → 3 |
.find(sub) | Find index (or -1) | "hello".find("ll") → 2 |
.startswith(s) | Starts with? | "hello".startswith("he") → True |
.endswith(s) | Ends with? | "hello".endswith("lo") → True |
.isdigit() | All digits? | "123".isdigit() → True |
.isalpha() | All letters? | "abc".isalpha() → True |
