Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 21 of 70

Python string methods: clean, search, split and join text

Use Python's most useful string methods to change case, trim spaces, search, replace, split text into pieces and join pieces back together.

14 minWorking with textUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonClean up, search, split and rebuild text using methods such as strip, lower, replace, split and join.

After this lesson you can take messy text, such as a name typed with extra spaces and odd capitals, clean it up, search inside it, split it into parts and put it back together.

Methods are functions on a value

A method is a function that belongs to a value. You call it by writing the value, a dot, the method name and brackets. For a string, "hello".upper() asks the string to give you an uppercase version of itself.

One rule matters more than any other. Strings are immutable, so a method never edits the string it is called on. It returns a new string. If you want to keep the answer, store it.

python
name = "maya rao"
name.upper()
print(name)
name = name.upper()
print(name)
result
maya rao
MAYA RAO

The first call did its job, but its answer was thrown away. Only the assignment on the third line kept it.

Changing case

Several methods change capitalisation.

python
title = "green LEAF books"
print(title.upper())
print(title.lower())
print(title.title())
print(title.capitalize())
print(title.swapcase())
result
GREEN LEAF BOOKS
green leaf books
Green Leaf Books
Green leaf books
GREEN leaf BOOKS

lower() is the one you will use most. Convert both sides to lowercase before comparing, and "Yes", "YES" and "yes" all become the same text.

Trimming whitespace

Text from forms, files and people often has stray spaces or new lines at the edges. strip() removes whitespace from both ends. lstrip() handles only the left and rstrip() only the right. Give them a string of characters and they remove those instead.

python
raw = "   Isha Menon \n"
print(repr(raw))
print(repr(raw.strip()))
print(repr("***sale***".strip("*")))
result
'   Isha Menon \n'
'Isha Menon'
'sale'

Using repr() shows the hidden spaces and the \n that a plain print would hide.

Searching

find() returns the position of the first match, counting from zero, or -1 when there is no match. count() says how many times something appears. startswith() and endswith() answer True or False. The in operator from earlier also works.

python
sentence = "the cat sat on the mat"
print(sentence.find("cat"))
print(sentence.find("dog"))
print(sentence.count("the"))
print(sentence.startswith("the"))
print(sentence.endswith("cat"))
print("sat" in sentence)
result
4
-1
2
True
False
True

A method called index() works like find() but raises a ValueError when the text is missing, which is better when absence means something has gone wrong.

Replacing

replace(old, new) returns a copy with every old swapped for new. A third argument limits how many replacements are made.

python
note = "Pay by cash. Cash only."
print(note.replace("Cash", "card"))
print(note.replace("ash", "ard", 1))
result
Pay by cash. card only.
Pay by card. Cash only.

Replacement is case sensitive, which is why only the second sentence changed in the first call.

Splitting and joining

split() cuts a string into a list. With no argument it splits on any run of whitespace, which is perfect for words. With an argument it cuts at that exact separator.

python
words = "red green  blue".split()
print(words)
row = "pen,12,0.75".split(",")
print(row)
print("a-b-c".split("-", 1))
result
['red', 'green', 'blue']
['pen', '12', '0.75']
['a', 'b-c']

join() does the opposite. You call it on the glue string and pass the list of pieces. All pieces must already be strings.

python
parts = ["2026", "11", "14"]
print("-".join(parts))
print(" ".join(["Green", "Leaf", "Books"]))
print("".join(["a", "b", "c"]))
result
2026-11-14
Green Leaf Books
abc

Note the order, which confuses many beginners. The separator comes first and join is the method.

Questions about characters

A group of methods returns True or False depending on what a string contains. They are handy for checking input.

python
print("2026".isdigit())
print("12ab".isdigit())
print("Maya".isalpha())
print("abc123".isalnum())
print("   ".isspace())
print("hello".islower(), "Hello".isupper())
result
True
False
True
True
True
True False

Be aware that "3.5".isdigit() is False, because the full stop is not a digit, and that an empty string gives False for these methods.

Chaining methods

Because each method returns a string, you can call another one straight on the result.

python
typed = "  GREEN leaf BOOKS  "
clean = typed.strip().lower().title()
print(clean)
result
Green Leaf Books

Read the chain from left to right: strip, then lowercase, then capitalise each word.

Finding the method you need

Strings have dozens of methods, and nobody remembers them all. You do not need to. The built-in dir("") lists every method that a string has, and help(str.split) shows a short description of one of them. Both work in the interactive prompt you met earlier in the course. Searching your memory for a verb is usually enough to find the right tool: to change something use replace, to cut something use split or a slice, to check something use a method starting with is or starts. When you are stuck, try the idea in the prompt on a tiny example before putting it in a program.

Common mistakes

  • Ignoring the return value. name.strip() alone does nothing useful. Write name = name.strip().
  • Swapping join around. It is "-".join(items), not items.join("-").
  • Using find() as a condition. It returns 0 for a match at the very start, and 0 is falsy. Compare with -1 or use in.
  • Joining numbers directly. ",".join([1, 2]) is a TypeError. Convert with str() first.
  • Expecting replace to ignore case. It does not, so lowercase the text first if that is what you want.

A video version of this topic is in the video course at /learn/python/.

Exercise

A form sends the text " Asha , Ben,Chloe , Dev ". Split it on commas, remove the extra spaces from every name, and print the names joined with a vertical bar and a space between each, like Asha | Ben | Chloe | Dev.

Show a possible answer
python
raw = "  Asha  ,  Ben,Chloe ,  Dev  "
pieces = raw.split(",")
names = []
for piece in pieces:
    names.append(piece.strip())
print(" | ".join(names))
result
Asha | Ben | Chloe | Dev

The loop and the list append method come later in the course. A shorter way, once you know comprehensions, is " | ".join(p.strip() for p in raw.split(",")).

Key points

  • A method is a function attached to a value and called with a dot, as in text.upper().
  • String methods never change the original string. They return a new one, so store the result.
  • strip, lower and upper clean up input. find, count, startswith and endswith search it.
  • split turns a string into a list of pieces, and join builds one string from a list.
  • isdigit, isalpha and similar methods answer yes-or-no questions about the characters in a string.

Check yourself

1. After text = 'hello', you run text.upper(). What is text afterwards?
2. What does 'a,b,c'.split(',') return?
3. What does '-'.join(['2026', '11', '14']) return?
4. What does ' Maya '.strip() return?
5. What does 'banana'.find('z') return?