Python String Methods
Table of Contents + β
In the last lesson you learned String Basics. You saw how to make text and join pieces together. Now comes the fun part. Python gives you ready-made tools that work on any string. So you do not have to write your own loop to change the case of letters or remove extra spaces. These tools are called string methods. They save you a lot of work.
π€ Why String Methods?
Real text is messy. A name someone types might come in as " riya SHARMA ". There are spaces around it. The case is all over the place. If you store it like that, your app looks broken.
You could write loops to fix each problem by hand. But that is slow and easy to get wrong. String methods are small built-in functions that do these common jobs for you in one line. Need lowercase? One call. Need the spaces gone? One call.
A method is just a function that belongs to a value. You call it by writing the value, then a dot, then the method name with parentheses, like name.upper().
π€ Changing the Case
The first thing people clean up is the case of the letters. Python gives you a method for every common case style.
Here is upper() and lower() on a simple word.
word = "Hello"
print(word.upper())print(word.lower())Output
HELLOhelloSo upper() makes every letter a capital letter. And lower() makes every letter small. You will use lower() a lot when you compare text. People type their email as Alex@Mail.com or alex@mail.com. To your program those look different. Lowercase them both first, and now they match.
There are two more case helpers that are nice for showing names.
name = "riya sharma"
print(name.title())print(name.capitalize())Output
Riya SharmaRiya sharmaSee the difference?
title()capitalizes the first letter of every word. Good for full names and headings.capitalize()capitalizes only the very first letter of the whole string, and lowercases the rest. Good for a single sentence.
βοΈ Removing Extra Spaces with strip()
Spaces at the start or end of text are a common headache. They sneak in when people copy and paste, or hit the space bar by accident. You usually cannot even see them.
The strip() method removes the spaces from the start and end of a string. It leaves the spaces in the middle alone.
messy = " hello world "
clean = messy.strip()print(clean)Output
hello worldThe two spaces in front are gone. The spaces at the end are gone too. But the single space between hello and world stayed. That one is in the middle. That is exactly what you want.
Tip
A common pattern is to strip and lowercase a userβs input in one go before you check it: user_input.strip().lower(). Each method returns a string, so you can chain the next one right onto it.
π Swapping Text with replace()
Sometimes you need to swap one piece of text for another. Maybe you want to fix a typo, or hide a word, or change a separator. The replace() method does this. You give it two things. The text to find, and the text to put in its place.
sentence = "I like cats. Cats are great."
result = sentence.replace("cats", "dogs")print(result)Output
I like dogs. Cats are great.Notice that only the lowercase cats changed. The capital Cats stayed the same. That is because replace() matches text exactly, including the case. Also notice it replaced every match it found, not just the first one.
πͺ Breaking Text Apart with split()
Often you have one long string and you want the separate pieces inside it. Like a full name where you want the first and last name on their own. Or a line of comma-separated values. The split() method takes a string and gives you back a list of smaller strings.
You tell split() what to cut on. That marker is called the separator.
full_name = "Riya Sharma"parts = full_name.split(" ")print(parts)
csv_line = "apple,banana,cherry"fruits = csv_line.split(",")print(fruits)Output
['Riya', 'Sharma']['apple', 'banana', 'cherry']So the first call cut the name on the space, and gave back two items. The second call cut on the comma, and gave back three. Each piece is now its own string inside a list, ready for you to use one by one.
If you call split() with no separator at all, it cuts on any spaces and is smart about extra ones. That is handy for breaking a sentence into words.
π§΅ Joining a List Back into Text with join()
The join() method is the opposite of split(). It takes a list of strings and glues them into one single string. The order looks a little backwards at first, so read it slowly. You write the separator first, then call .join() on it, and pass the list inside.
words = ["Learn", "Python", "today"]
sentence = " ".join(words)print(sentence)
path = "/".join(["users", "riya", "documents"])print(path)Output
Learn Python todayusers/riya/documentsThe " " in front is the glue that goes between the pieces. So " ".join(words) puts a space between each word. And "/".join(...) puts a slash between each part, which is how you build a file path. One important rule. Every item in the list must already be a string, or join() will raise an error.
Note
split() turns text into a list. join() turns a list back into text. They are a matched pair, and you will often use them together: split a string apart, fix the pieces, then join them back.
β οΈ Strings Are Immutable: Store the Result
This is the single most important idea on this page, so slow down here. In Python a string is immutable. That means once a string exists, it can never be changed. Not by you, not by any method.
So what does upper() actually do? It does not change your string. It makes a brand new string and hands it back to you. Your original is untouched.
That leads to the mistake almost everyone makes once.
name = "alex"
# β Avoid: calling the method but throwing away the resultname.upper()print(name)Output
alexThe name is still lowercase. The upper() call did make an uppercase string, but nobody stored it, so it was lost. You have to catch the new string in a variable.
name = "alex"
# β
Good: store what the method returnsname = name.upper()print(name)Output
ALEXBy writing name = name.upper() you point name at the new uppercase string. Every method on this page works this way. They all return a new string, and you must store it to keep it.
π§Ή A Real Example: Cleaning Up a Messy Name
Let us put the methods together on a real job. Someone signed up and typed their name as " riya SHARMA ". There are extra spaces around it, and the case is a mess. We want a clean, nicely formatted name.
We will fix it step by step so you can see what each method does.
raw = " riya SHARMA "
trimmed = raw.strip() # remove the outer spaceslowered = trimmed.lower() # make everything lowercase firstclean = lowered.title() # then capitalize each word
print(f"Welcome, {clean}!")Output
Welcome, Riya Sharma!Walking through it:
strip()removed the spaces at the start and end, giving"riya SHARMA".lower()turned everything small, giving"riya sharma". We do this first sotitle()has a clean base.title()capitalized the first letter of each word, giving"Riya Sharma".
Because each method returns a string, you can do the whole thing in one chained line once you are comfortable.
raw = " riya SHARMA "
clean = raw.strip().lower().title()print(f"Welcome, {clean}!")Output
Welcome, Riya Sharma!Read the chain left to right. First strip the spaces, then lowercase the result, then title-case that. Each method runs on whatever the one before it handed back.
π Quick Reference
Here are the methods from this lesson in one place.
| Method | What it does | Example result |
|---|---|---|
upper() | All letters become capitals | "hi".upper() gives "HI" |
lower() | All letters become small | "HI".lower() gives "hi" |
strip() | Removes spaces from start and end | " hi ".strip() gives "hi" |
replace(a, b) | Swaps every a for b | "cat".replace("c", "b") gives "bat" |
split(sep) | Cuts text into a list | "a,b".split(",") gives ["a", "b"] |
join(list) | Glues a list into one string | "-".join(["a", "b"]) gives "a-b" |
title() | Capitalizes each word | "hi there".title() gives "Hi There" |
capitalize() | Capitalizes only the first letter | "hi there".capitalize() gives "Hi there" |
β οΈ Common Mistakes
A few traps catch almost everyone the first time.
- Forgetting to store the result.
text.strip()on its own does nothing useful. Writetext = text.strip()so you keep the cleaned string. - Expecting
replace()to change only the first match. It changes every match in the string. If you need just the first one,replace()takes a count, liketext.replace("a", "b", 1). - Thinking
replace()ignores case. It does not."Cats".replace("cats", "dogs")does nothing, because the case is different. Lowercase first if you need a case-insensitive swap. - Passing a list with non-strings to
join(). Every item must be a string."-".join([1, 2, 3])raises an error. Convert the numbers to strings first.
β Best Practices
- Normalize user input early. A quick
value.strip().lower()on text the moment it arrives saves you bugs later. - Use
title()for display names and headings, but remember it can mishandle names like"o'brien". For perfect names, store the exact text the person typed. - Chain methods when the steps are simple and clear, like
raw.strip().lower(). If the chain gets long and hard to read, split it into named steps instead. - Reach for
split()andjoin()as a pair whenever you need to pull text apart, fix the pieces, and put it back together.
π§© What Youβve Learned
β String methods are built-in tools that do common text jobs for you in one line.
β
upper(), lower(), title(), and capitalize() change the case of letters in different ways.
β
strip() removes spaces from the start and end, replace() swaps text, split() turns text into a list, and join() turns a list back into text.
β Strings are immutable, so every method returns a new string and never changes the original.
β
You must store what a method returns, usually with name = name.method(), or the result is lost.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
Why does `name.upper()` on its own leave `name` unchanged?
Why: Strings cannot be changed in place, so methods return a new string that you must store to keep.
- 2
What does `"a,b,c".split(",")` return?
Why: split() cuts the string on the separator and returns a list of the pieces.
- 3
Which call correctly joins `["users", "riya"]` into `"users/riya"`?
Why: You write the separator first, then call .join() on it and pass the list inside.
- 4
What does `"riya sharma".title()` produce?
Why: title() capitalizes the first letter of every word, while capitalize() would only capitalize the very first letter.
π Whatβs Next?
You can now clean and reshape whole strings. Next you will learn how to grab just a piece of a string by its position. That is one of the most used skills in Python.