Module 5 · Beginner · Working with text

How to clean and split text in Python

Clean and split text in Python: strip spaces, fix case, replace characters, split and join, partition, remove punctuation and tidy messy names.

By theprogrammers team · · 8 min read

A Google Form for a college event collects 400 names. Some people typed " ahana khan", some "AHANA KHAN ", and one wrote "Ahana Khan" with two spaces. To a computer these are three different names, so your count of unique students comes out wrong. Before you can analyse text, you have to clean and split text in Python: remove extra spaces, fix the case, and break lines into the pieces you need.

This is unglamorous work, but data analysts often say cleaning takes more of their time than analysis. The good news is that a handful of string methods handle most of it. This lesson covers them with real messy examples: names, phone numbers, addresses and CSV-like lines.

What you need first: Python strings and string methods and Python lists.

Key terms

  • Whitespace: characters you can't see: spaces, tabs (\t) and new lines (\n).
  • Delimiter: the character that separates pieces of text, such as the comma in "Pune,Delhi,Goa".
  • Split: break one string into a list of smaller strings at a delimiter.
  • Join: the reverse, glue a list of strings into one string with a delimiter between them.
  • Normalise: convert different spellings of the same thing into one standard form, like "PUNE", " pune" and "Pune" all becoming "Pune".

Removing extra spaces with strip()

strip() removes whitespace from both ends. It never touches spaces in the middle.

raw = "   Ahana Khan \n"
print(repr(raw.strip()))
print(repr(raw.lstrip()))
print(repr(raw.rstrip()))
'Ahana Khan'
'Ahana Khan \n'
'   Ahana Khan'

repr() shows a string with its quotes and hidden characters such as \n, so you can see exactly what's there. It's the best tool for debugging text.

strip can also remove specific characters from the ends. You give it a set of characters, not a word:

print("###Total: 450###".strip("#"))
print("₹1,250.00".lstrip("₹"))
print("www.example.com".strip("w."))
Total: 450
1,250.00
example.com

The last one works, but be careful: strip("w.") removes any w or . from the ends, in any order. It isn't "remove the text w.". To remove a fixed beginning or ending, use removeprefix and removesuffix (Python 3.9 or newer):

print("report_final.csv".removesuffix(".csv"))
print("Mr. Sharma".removeprefix("Mr. "))
report_final
Sharma

Fixing spaces in the middle

"Ahana Khan" has two spaces in the middle. split() with no argument splits on any run of whitespace and ignores the ends, so splitting and joining again collapses the spaces:

messy = "  Ahana    Khan\t "
print(" ".join(messy.split()))
Ahana Khan

This one-liner is worth remembering.

Fixing case

Method"aHANA kHAN" becomes
lower()ahana khan
upper()AHANA KHAN
title()Ahana Khan
capitalize()Ahana khan
swapcase()Ahana Khan
casefold()ahana khan

For comparing text, use lower() (or casefold(), which also handles some non-English letters, such as the German ß). For displaying names, title() is close, but it has a known quirk:

print("o'brien".title())
print("rahul's laptop".title())
O'Brien
Rahul'S Laptop

title() capitalises the letter after any non-letter, including an apostrophe. For names you'll display to people, check the results, or capitalise word by word with word.capitalize().

Replacing characters

replace(old, new) swaps every match. Chain several to clean a value:

phone = "+91 98765-43210"
digits = phone.replace("+91", "").replace(" ", "").replace("-", "")
print(digits, len(digits))
9876543210 10

replace also takes a count: "a-b-c".replace("-", "+", 1) changes only the first one, giving "a+b-c".

When there are many different characters to remove, replace chains get long. Keep only the characters you want instead:

phone = "(+91) 98765 43210"
digits = "".join(ch for ch in phone if ch.isdigit())
print(digits[-10:])
9876543210

[-10:] keeps the last 10 digits, which drops the country code.

Splitting text into pieces

split(delimiter) breaks a string wherever the delimiter appears:

line = "Ahana,21,Pune,88"
parts = line.split(",")
print(parts)
name, age, city, marks = parts
print(name, int(marks) + 2)
['Ahana', '21', 'Pune', '88']
Ahana 90

The pieces are always strings, so convert numbers with int() or float().

Splitting with an explicit delimiter keeps empty pieces, while split() with no argument doesn't:

print("a,,b".split(","))
print("a  b".split(" "))
print("a  b".split())
['a', '', 'b']
['a', '', 'b']
['a', 'b']

To split only a limited number of times, pass maxsplit. rsplit does the same from the right:

address = "Flat 4, Shanti Apartments, MG Road, Pune"
print(address.split(", ", 1))
print(address.rsplit(", ", 1))
['Flat 4', 'Shanti Apartments, MG Road, Pune']
['Flat 4, Shanti Apartments, MG Road', 'Pune']

rsplit(", ", 1) is a neat way to get the city from the end of an address.

Splitting lines

splitlines() splits text into lines and handles both Windows (\r\n) and Mac/Linux (\n) line endings:

text = "Line one\r\nLine two\nLine three"
print(text.splitlines())
['Line one', 'Line two', 'Line three']

partition: split once, always three parts

partition(sep) splits at the first sep and always returns three parts: before, the separator, after. It never raises an error, even when the separator is missing:

email = "ahana.khan@college.edu.in"
user, at, domain = email.partition("@")
print(user, domain)

print("no-at-sign".partition("@"))
ahana.khan college.edu.in
('no-at-sign', '', '')

Joining pieces back together

join is called on the separator, with the list as the argument. It looks backwards at first:

cities = ["Pune", "Delhi", "Goa"]
print(", ".join(cities))
print(" -> ".join(cities))
print("".join(["2", "0", "2", "6"]))
Pune, Delhi, Goa
Pune -> Delhi -> Goa
2026

Every item must be a string. ", ".join([1, 2, 3]) raises TypeError: sequence item 0: expected str instance, int found. Convert first: ", ".join(str(n) for n in [1, 2, 3]).

Removing punctuation

str.maketrans and translate delete a whole set of characters in one pass. The string module has the list of ASCII punctuation ready:

import string

review = "Great food!!! Fast delivery, but... the naan was cold?"
table = str.maketrans("", "", string.punctuation)
clean = review.translate(table).lower()
print(clean)
print(clean.split())
great food fast delivery but the naan was cold
['great', 'food', 'fast', 'delivery', 'but', 'the', 'naan', 'was', 'cold']

This is the first step of most text analysis: lower-case, remove punctuation, split into words.

A full cleaning function

Here's everything together, cleaning the messy form data from the opening:

def clean_name(raw):
    words = raw.split()                  # splits on any whitespace, drops the ends
    return " ".join(w.capitalize() for w in words)

responses = ["  ahana khan", "AHANA KHAN ", "Ahana  Khan", "rohan\tmehta"]
cleaned = [clean_name(r) for r in responses]
print(cleaned)
print(len(set(responses)), "->", len(set(cleaned)), "unique names")
['Ahana Khan', 'Ahana Khan', 'Ahana Khan', 'Rohan Mehta']
4 -> 2 unique names

Without cleaning, you'd have counted four different people.

Where text cleaning is used

  • Data analysis: pandas has the same methods on whole columns: df["name"].str.strip().str.title().
  • Machine learning on text (spam filters, review sentiment): lower-casing, removing punctuation and splitting into words is the standard first step, called tokenisation.
  • Forms and sign-ups: tidying phone numbers, emails and PIN codes before saving them.
  • Log files: splitting each line into date, level and message.

When patterns get more complex, such as "find every 6-digit PIN code", use regular expressions.

Common mistakes

  • Forgetting that strings can't change. name.strip() returns a new string; it doesn't change name. Write name = name.strip().
  • split(" ") instead of split(), which leaves empty strings when there are double spaces.
  • Thinking strip("abc") removes the word "abc". It removes any of those characters from the ends. Use removeprefix/removesuffix.
  • Splitting CSV lines on commas when a field itself contains a comma, like "Pune, MH". Use the csv module for real CSV files; see Python file handling.

Practice

  1. Clean " HELLO world " into "Hello World".
Show the answer
text = "   HELLO   world  "
print(" ".join(text.split()).title())
Hello World
  1. From "2026-12-03", get the year, month and day as integers.
Show the answer
year, month, day = map(int, "2026-12-03".split("-"))
print(year, month, day)
2026 12 3

int("03") gives 3; leading zeros are fine for int.

  1. Count the words in this review, ignoring punctuation and case, and find how many are unique.
review = "Good food. Good service. Good price!"
Show the answer
import string

review = "Good food. Good service. Good price!"
words = review.translate(str.maketrans("", "", string.punctuation)).lower().split()
print(len(words), len(set(words)))
6 4

The unique words are good, food, service and price.

  1. Given "Name: Ahana | City: Pune | Marks: 88", build the dictionary {'Name': 'Ahana', 'City': 'Pune', 'Marks': '88'}.
Show the answer

Split on " | " to get each field, then partition each field at ": ":

text = "Name: Ahana | City: Pune | Marks: 88"
record = {}
for field in text.split(" | "):
    key, _, value = field.partition(": ")
    record[key] = value
print(record)
{'Name': 'Ahana', 'City': 'Pune', 'Marks': '88'}
  1. Get the file extension from "marks.final.v2.xlsx".
Show the answer

rsplit from the right with one split, or rpartition:

filename = "marks.final.v2.xlsx"
print(filename.rsplit(".", 1)[1])
print(filename.rpartition(".")[2])
xlsx
xlsx

split(".")[1] would wrongly give final. For real file paths, pathlib has .suffix; see working with files and folders using pathlib.

Interview questions

What is the difference between split() and split(" ")?

split() with no argument splits on any run of whitespace (spaces, tabs, new lines) and drops empty strings and the ends. split(" ") splits on each single space, so double spaces give empty strings in the result.

Why is join called on the separator, as in ", ".join(items)?

join is a string method, and the string it's called on is what goes between the items. This lets it work on any iterable of strings: a list, a tuple or a generator.

How do you remove all punctuation from a string?

text.translate(str.maketrans("", "", string.punctuation)) deletes every ASCII punctuation character in one pass. A regular expression like re.sub(r"[^\w\s]", "", text) also works and handles more symbols.

Key takeaways

  • strip() cleans the ends; " ".join(text.split()) also collapses spaces in the middle.
  • Lower-case text before comparing it; check title() results on names with apostrophes.
  • split(sep) breaks text into a list of strings; convert numbers afterwards.
  • partition and rsplit(sep, 1) split once, from the left or right.
  • sep.join(list) rebuilds a string, and every item must be a string.
  • String methods return new strings; assign the result back.

Frequently asked questions

How do I split a string by more than one delimiter?

Replace the extra delimiters with one first, as in text.replace(";", ",").split(","), or use re.split(r"[;,]", text) from the re module.

How do I remove newline characters from a string?

text.strip() removes them from the ends. To remove them everywhere, use text.replace("\n", " "), or " ".join(text.split()) to turn all whitespace into single spaces.

What does strip() remove by default?

All leading and trailing whitespace: spaces, tabs, new lines, carriage returns and a few other Unicode space characters.

What to learn next

  1. Find patterns like phone numbers and emails with regular expressions in Python.
  2. Understand why some characters cause trouble in Unicode and text encodings.
  3. Revise the basics in Python strings and string methods.