String Methods
Learn how to transform, search, and clean text using Python's built-in string methods — the everyday tools every Python programmer reaches for.
Strings are everywhere: names, messages, addresses, emails. Real-world text is messy — it has extra spaces, odd capitalization, or needs to be split apart. Python gives every string a built-in toolkit called methods. A method is like a helper function that lives on the string itself. You call it with a dot: "hello".upper(). In this lesson you will learn the most useful ones.
See it in action
— step through the idea, then dive into the details below.Strings Have Built-In Tools
Every string in Python comes with a built-in toolkit of methods — helpers you call with a dot. They let you transform, search, and clean text without writing any complex code yourself.
#Changing Case
Three methods handle capitalization. They are useful for displaying names nicely or comparing text without worrying about whether someone typed 'PYTHON' or 'python'.
name = "alice wonder"
print(name.upper()) # all capitals
print(name.lower()) # all lowercase
print(name.title()) # first letter of each word capitalisedMethods are tools on a Swiss Army knife
Think of a string as a piece of paper, and methods as the tools clipped to the side. You pick the tool you need — upper(), lower(), strip() — and it does its job, handing you back a new piece of paper with the result.
#Strings Are Immutable — Methods Return NEW Strings
This is one of the most important things to understand: calling a method does not change the original string. It always hands you back a brand-new string. You need to save that result in a variable if you want to use it.
greeting = "hello"
# This does NOT change greeting
greeting.upper()
print(greeting) # still lowercase!
# You must capture the result
louder = greeting.upper()
print(louder)Forgetting to save the result
A very common beginner mistake:
``python word = "python" word.upper() # result is thrown away! print(word) # still 'python' ``
Always assign the result: word = word.upper().
#Cleaning Up Whitespace with strip()
When users type text into a form, they often accidentally add spaces at the start or end. strip() removes those for you. lstrip() removes only from the left, and rstrip() only from the right.
user_input = " alice@example.com "
cleaned = user_input.strip()
print(repr(cleaned)) # repr() shows quotes so you can see spaces clearly#Finding and Replacing Text
replace(old, new) swaps every occurrence of one piece of text with another. find(text) tells you where something appears — it returns the index (position number), or -1 if not found.
sentence = "I love cats. Cats are great."
print(sentence.replace("cats", "dogs"))
print(sentence.replace("Cats", "Dogs"))text = "Python is fun"
position = text.find("fun")
print(position) # index where 'fun' starts
missing = text.find("boring")
print(missing) # -1 means not found#Counting and Checking
count(text) tells you how many times something appears. startswith(text) and endswith(text) check the beginning or end of a string and return True or False. isdigit() checks whether every character is a number.
sentence = "banana banana banana"
print(sentence.count("banana")) # how many times?
print(sentence.startswith("banana")) # True or False?
print(sentence.endswith("apple")) # True or False?
code = "12345"
print(code.isdigit()) # True — all digits#Splitting and Joining — A Power Pair
split() breaks a string into a list of pieces. join() does the reverse — it glues a list of strings back together. They work perfectly as a team for reshaping text.
csv_line = "Alice,Bob,Charlie,Diana"
names = csv_line.split(",") # split on the comma
print(names)
print(type(names))names = ["Alice", "Bob", "Charlie"]
# join() is called on the SEPARATOR, not the list
result = " | ".join(names)
print(result)split() with no argument splits on any whitespace
" hello world ".split() returns ['hello', 'world'] — it automatically handles multiple spaces and strips them. Very handy for cleaning up messy input.
#Method Chaining
Because each method returns a new string, you can call another method immediately on that result. This is called chaining — reading left to right, each method hands its output to the next.
raw = " HELLO, world! "
# strip, then lower, then replace — all in one line
cleaned = raw.strip().lower().replace(",", "")
print(cleaned)#A Practical Example: Cleaning User Input
Here is how you might combine several methods to clean up a username before saving it to a database.
raw_username = " Ali Khan "
username = raw_username.strip().lower().replace(" ", "_")
print(username)What does this code print? ```python word = "python" word.upper() print(word) ```
Key takeaways
- String methods are called with a dot: `text.method()` — they are built right into every string.
- Methods never change the original string; they always return a new one. Always save the result.
- `strip()`, `replace()`, and `lower()` are your best friends for cleaning messy text.
- `split()` turns a string into a list; `join()` turns a list back into a string — use them as a pair.
- You can chain methods one after another to transform text in a single readable line.
What does this code print?
greeting = "hello"
greeting.upper()
print(greeting)This code should print 'alice@example.com' (all lowercase, no extra spaces), but it doesn't work as expected. What is wrong?
email = " Alice@Example.COM "
email.strip()
email.lower()
print(email)Complete the code so it prints 'PYTHON IS FUN'.
text = "python is fun" print(text.())
Put these lines in the right order so the code splits the sentence into words and prints them joined by a dash, like: 'I-love-Python'.
result = "-".join(words)
sentence = "I love Python"
words = sentence.split()
print(result)
You have received a messy list of email addresses as a single string: " Alice@Example.COM , bob@GMAIL.COM, CHARLIE@outlook.com ". Your task: split it on the comma, then clean each email by stripping whitespace and converting to lowercase. Print each cleaned email on its own line.
Try it live — edit the code and hit Run to execute real Python: