Skip to content
Python

Python String Methods and Slicing: split(), join(), strip() and Reversing Strings

Ihsan Ullah · 11 min read
Python string methods, Lesson 20 of the Python course: split(), join(), strip(), replace() and slicing

Python course · Module 4: Data structures · Lesson 20 of 63

Quick answer: A slice text[start:stop:step] takes part of a string: "PEN-0042"[0:3] gives "PEN", and text[::-1] gives the string reversed. String methods are tools you call with a dot, like name.strip(), name.upper(), line.split(",") or ", ".join(items). Strings cannot change, so methods like strip() and upper() return a new string and leave the original alone: write name = name.strip() to keep the result.

In this lesson you will learn:

  • how to slice a string with start, stop and step, and reverse it with [::-1]
  • why name.upper() alone does not change name
  • how to clean text with strip(), lower(), upper() and replace()
  • how to turn text into a list with split() and back with join()
  • how to search with in, find(), startswith(), endswith() and count(), and how to chain methods

Before you start: finish Lesson 19, Python List vs Tuple vs Set vs Dict: Which One to Use. You should also know string indexes from Lesson 7, Python Strings and f-Strings: Quotes, Escapes and Formatting: text[0] is the first character, text[-1] the last, an index past the end raises IndexError, and text[0] = "x" raises TypeError because strings are immutable. This lesson does not repeat those. All examples were tested on Python 3.14.6 and gave exactly the same output on Python 3.15.2, the newest release on python.org.

Slicing a string

A slice text[start:stop] gives the characters from start up to, but not including, stop. Our running example is a product code:

code = "PEN-0042-BLUE"
print(code[0:3])
print(code[4:8])
print(code[9:])
print(code[:3])
print(code[-4:])
print(code[4:100])
print(code[:3] + code[3:])
PEN
0042
BLUE
PEN
BLUE
0042-BLUE
PEN-0042-BLUE
  • code[0:3] takes indexes 0, 1 and 2. Index 3, the dash, is the stop, so it is left out.
  • Leave out start to begin at the start, and leave out stop to go to the end. code[-4:] means “the last four characters”.
  • A stop past the end is not an error: code[4:100] just stops at the end. The Python tutorial says “out of range slice indexes are handled gracefully”.
  • The tutorial also notes that “the start is always included, and the end always excluded”, so code[:3] + code[3:] gives back the whole string.

These are the same rules as list slicing in Lesson 15. A slice always makes a new string; code itself never changes.

Slicing with a step, and reversing a string

A third number is the step. [::2] takes every second character. A negative step walks backwards:

word = "Notebook"
print(word[::2])
print(word[1::2])
print(word[::-1])
print(word[-1:-5:-1])
for w in ["level", "Notebook"]:
    print(w, w == w[::-1])
Ntbo
oeok
koobetoN
koob
level True
Notebook False

word[::-1] is the usual way to reverse a string in Python: start at the end and step back one character at a time. In Lesson 14 you reversed a word with a loop; this slice does it in one step. word[-1:-5:-1] starts at the last character and stops before index -5, so it gives four characters. The last loop checks for palindromes, words that read the same backwards.

Methods return a new string

Strings are immutable, so a method cannot change the string you call it on. A method like upper() gives you a new string instead. This catches many beginners:

item = "notebook"
item.upper()
print(item)
item = item.upper()
print(item)
notebook
NOTEBOOK

Line 2 made "NOTEBOOK" and threw it away, because nothing stored it. Line 4 stores the new string back in item. The Built-in Types page describes upper() and lower() with the words “Return a copy of the string”, and the same idea applies to strip() and replace().

Change case: upper() and lower()

answer = "YeS"
print(answer.upper())
print(answer.lower())
print(answer.lower() == "yes")
print("Pen" == "pen")
print("Pen".lower() == "pen".lower())
YES
yes
True
False
True

== treats capital and small letters as different, so "Pen" == "pen" is False. To compare text that a user typed, turn both sides to lower case first. This is how you accept yes, YES and YeS with one test.

Remove spaces: strip()

Text from input() (Lesson 10) or from a file often has extra spaces. strip() removes them from both ends; lstrip() only from the left and rstrip() only from the right:

typed = "   Notebook  "
print(f"[{typed}]")
print(f"[{typed.strip()}]")
print(f"[{typed.lstrip()}]")
print(f"[{typed.rstrip()}]")
print("---Pen---".strip("-"))
[   Notebook  ]
[Notebook]
[Notebook  ]
[   Notebook]
Pen

The square brackets are only there to show where the spaces are. strip() never touches spaces in the middle. With an argument, it removes those characters instead of spaces, so strip("-") removed the dashes. Without one, it removes all whitespace, including tabs and new lines.

Replace text: replace()

replace(old, new) swaps every old for new. A third argument limits how many are replaced:

note = "Blue pen, red pen, black pen"
print(note.replace("pen", "marker"))
print(note.replace("pen", "marker", 1))
price_text = "1,250"
print(int(price_text.replace(",", "")) + 50)
print(note.replace("Pen", "marker"))
Blue marker, red marker, black marker
Blue marker, red pen, black pen
1300
Blue pen, red pen, black pen

Replacing "," with an empty string turns "1,250" into "1250", which int() from Lesson 8 can convert. The last line changed nothing, because replace() is case sensitive and there is no "Pen" with a capital P in note. No error is raised.

Split text into a list: split()

split(sep) cuts a string at every sep and returns a list of the pieces. This is how you read a line of data, such as a product, its price and its stock:

line = "Notebook,450,12"
parts = line.split(",")
print(parts)
name, price, stock = parts
print(name, int(price) * int(stock))

print("  learn   Python   today ".split())
print("Pen, Notebook, Ruler".split(","))
print("Pen, Notebook, Ruler".split(", "))
['Notebook', '450', '12']
Notebook 5400
['learn', 'Python', 'today']
['Pen', ' Notebook', ' Ruler']
['Pen', 'Notebook', 'Ruler']

The pieces are always strings, so we convert '450' and '12' with int() before multiplying. Unpacking the list into three names works like tuple unpacking in Lesson 16.

With no argument, split() splits on any run of spaces and ignores spaces at the ends. The docs say “runs of consecutive whitespace are regarded as a single separator”. Now look at the last two lines. Splitting on "," left a space at the start of ' Notebook' and ' Ruler'. Split on ", " instead, or strip() each piece.

Join a list into text: join()

join() is the opposite of split(). You call it on the separator, and pass the list:

items = ["Pen", "Notebook", "Ruler"]
print(", ".join(items))
print(" + ".join(items))
print("".join(["P", "e", "n"]))
words = "learn   Python   today".split()
print(" ".join(words))
Pen, Notebook, Ruler
Pen + Notebook + Ruler
Pen
learn Python today

The order looks backwards at first: ", ".join(items), not items.join(", "). The docs explain that “the separator between elements is the string providing this method”. The last two lines show a handy pair: split() then " ".join() squeezes many spaces into one.

join() only accepts strings. A list of numbers fails:

prices = [60, 450, 40]
print(", ".join(prices))
Traceback (most recent call last):
  File "/home/learner/python-course/err1_join_numbers.py", line 2, in <module>
    print(", ".join(prices))
          ~~~~~~~~~^^^^^^^^
TypeError: sequence item 0: expected str instance, int found

Convert each number with str() first. With what you know so far, a for loop does it (Lesson 21 shows a shorter way):

prices = [60, 450, 40]
texts = []
for price in prices:
    texts.append(str(price))
print(", ".join(texts))
60, 450, 40

Search a string: in, find(), startswith() and count()

email = "sara.ahmed@example.com"
print(email.find("@"))
print(email.find("#"))
print("@" in email)
at = email.find("@")
print(email[:at])
print(email[at + 1:])
print(email.startswith("sara"))
print(email.endswith(".com"))
print(email.count("a"))
10
-1
True
sara.ahmed
example.com
True
True
4
  • find() returns the index of the first match, here 10, or -1 if there is none.
  • in simply answers True or False. The docs advise: use find() “only if you need to know the position”, and use in to check if one string is inside another.
  • find() and slicing work well together: email[:at] is the part before the @.
  • startswith() and endswith() check the beginning and the end.
  • count("a") counts how many times "a" appears.

Using find() as a yes/no test is a classic bug:

order = "Pen, Notebook"
if order.find("Pen"):
    print("Pen ordered")
else:
    print("No pen ordered")
No pen ordered

"Pen" is at index 0, so find() returned 0, and 0 counts as false in an if (truthiness, from Lesson 8). A missing word gives -1, which counts as true. Write if "Pen" in order: instead.

Chaining methods

Because strip(), upper(), lower() and replace() each return a new string, you can call the next method on the result straight away. Python runs the chain from left to right:

raw = "  PEN-0042-blue  "
print(raw.strip().upper())
print(raw.strip().lower().replace("-", " "))
print(raw.strip().split("-"))
code, number, colour = raw.strip().upper().split("-")
print(f"Product {code}, number {int(number)}, colour {colour}")
PEN-0042-BLUE
pen 0042 blue
['PEN', '0042', 'blue']
Product PEN, number 42, colour BLUE

Read raw.strip().upper().split("-") as: remove the spaces, then make it upper case, then cut at each dash. split() must come last here, because it returns a list, and a list has no upper() method. Keep chains short enough to read in one go.

Try it yourself

Exercise 1: Palindromes

For each word in ["Racecar", "Python", "Level"], print the word and whether it is a palindrome. Capital letters should not matter.

Exercise 2: Read a data line

The line "Ruler;40;30" holds a product, its price and its stock, separated by semicolons. Print Ruler: 30 in stock, worth 1200 rupees, calculating the value.

Exercise 3: Clean an email

A user typed " Sara.Ahmed@Example.COM ". Remove the spaces, make it lower case, print the user name and the domain separately, and check that it ends with .com.

Solutions

Solution 1

for word in ["Racecar", "Python", "Level"]:
    small = word.lower()
    print(word, small == small[::-1])
Racecar True
Python False
Level True

lower() makes "Racecar" into "racecar", which equals its reverse.

Solution 2

line = "Ruler;40;30"
name, price, stock = line.split(";")
value = int(price) * int(stock)
print(f"{name}: {stock} in stock, worth {value} rupees")
Ruler: 30 in stock, worth 1200 rupees

split(";") gives three strings, and int() converts two of them for the multiplication.

Solution 3

typed = "  Sara.Ahmed@Example.COM "
email = typed.strip().lower()
user, domain = email.split("@")
print(email)
print("User:", user)
print("Domain:", domain)
print("Ends with .com:", email.endswith(".com"))
sara.ahmed@example.com
User: sara.ahmed
Domain: example.com
Ends with .com: True

The chain cleans the text once, and split("@") gives exactly two parts to unpack.

Common mistakes

  • Calling a method without saving the result. item.upper() alone leaves item unchanged. Write item = item.upper().
  • Using find() in an if. It returns 0 for a match at the start and -1 for no match, so the test is wrong both ways. Use in.
  • Joining numbers. ", ".join([60, 450, 40]) gives TypeError: sequence item 0: expected str instance, int found. Convert each item with str() first.
  • Splitting on "," when the text has ", ". The pieces keep a leading space, like ' Notebook'. Split on ", " or strip() each piece.
  • Guessing method names. item.uppercase() gives AttributeError: 'str' object has no attribute 'uppercase'. The method is upper(); the Built-in Types page lists every string method.

Frequently asked questions

How do you reverse a string in Python?

Use a slice with a step of -1: "Notebook"[::-1] gives "koobetoN". It starts at the last character and walks back to the first. The original string does not change; you get a new one.

How do I check if a string contains a word in Python?

Use in: "@" in email is True when the text contains "@". It is case sensitive, so compare text.lower() if capital letters should not matter. Use find() only when you also need the position.

How do I split a string into a list in Python?

Call split(): "Pen,Notebook".split(",") gives ['Pen', 'Notebook']. With no argument, split() splits on any amount of whitespace and drops empty pieces. To go back from a list to a string, use ", ".join(the_list).

Summary

  • text[start:stop:step] makes a new string; the stop is never included, and text[::-1] reverses.
  • Strings are immutable, so methods like strip() return new strings: save the result with text = text.strip().
  • upper(), lower(), strip() and replace() clean text; replace() and == are case sensitive.
  • split() turns text into a list of strings, and "sep".join(list) turns a list of strings back into text.
  • Use in for yes/no checks, find() for positions, and chain methods left to right.

Next lesson

Next: Lesson 21, Python List, Dict and Set Comprehensions.

Sources

Ihsan Ullah

Written & tested by Ihsan Ullah

Data analyst with 3 years of experience and a Bachelor's degree in Computer Science. I write clear, practical guides on data, SQL, Python and AI.

More about me →

Leave a comment

Your email address will not be published. Required fields are marked *