Skip to content

Intermediate · Working with data · topic 28 of 50 · 20 min

String processing

Explanation

Real text is messy: extra spaces, mixed capital letters and stray symbols. String methods such as strip, lower, replace and split clean it up, and isdigit or isalpha check what a piece of text contains. With join, zfill and ljust you can then build neat reports.

Cleaning messy input

python
raw = "   rAVI   kumar  "
print(raw.strip())
print(" ".join(raw.split()).title())
phone = " 98765 43210 "
print(phone.replace(" ", ""))
strip trims the ends; split and join also squash the spaces in the middle.
Think of it like this: Cleaning text is like preparing vegetables before cooking. strip washes off the mud at the ends, lower makes all the pieces the same, replace cuts out the bad bits and split chops them into pieces you can use.
MethodWhat it doesExample result
strip()removes spaces (and new lines) at both ends" hi " → "hi"
lower() / upper() / title()changes capital letters"rAVI" → "ravi" / "RAVI" / "Ravi"
replace(a, b)swaps every a for b"9-8-7" → "987" with replace("-", "")
split(sep)cuts into a list of pieces"a,b".split(",") → ["a", "b"]
sep.join(list)glues pieces together with sep"-".join(["a", "b"]) → "a-b"
startswith / endswithchecks the start or end"INV-7".startswith("INV")
isdigit / isalphaonly digits? only letters?"560001".isdigit() → True
zfill(n) / ljust(n) / rjust(n)pads to a width"7".zfill(3) → "007"

Splitting lines and words

python
notes = """Rice 5 kg
Dal 2 kg

Oil 1 litre"""
lines = notes.splitlines()
print(lines)
print("Oil 1 litre".split())
print("a  b".split(" "))
A triple-quoted string can span many lines. splitlines cuts it into lines.
Tip: split() with no argument splits on any run of spaces, tabs or new lines, and never gives empty pieces. split(" ") splits on each single space, so two spaces in a row give an empty string "".

Counting words

python
text = "Chai is hot. Chai is sweet!"
for mark in ".,!?":
    text = text.replace(mark, "")
counts = {}
for word in text.lower().split():
    counts[word] = counts.get(word, 0) + 1
print(counts)
Remove punctuation, make everything lower case, then count.

Checking what text contains

python
print("560001".isdigit())
print("Asha".isalpha())
print("Asha Rao".isalpha())
print("-5".isdigit(), "2.5".isdigit(), "".isdigit())
A space, a minus sign or a decimal point is not a digit or a letter.
Careful: Strings never change in place; they are immutable. name.strip() gives you a NEW string and leaves name as it was. Write name = name.strip() to keep the result. Forgetting this is one of the most common bugs.

Padding and building reports

python
print(str(42).zfill(5))
items = [("Tea", 20), ("Samosa", 15), ("Jalebi", 40)]
lines = []
for name, price in items:
    lines.append(name.ljust(10, ".") + str(price).rjust(5))
report = "\n".join(lines)
print(report)
ljust pads on the right, rjust pads on the left, so the prices line up.

Build each line of a report as a string, collect the lines in a list, and join them with "\n" (a new line) at the end. This is cleaner and faster than adding strings together again and again in a loop.

Watch the lesson

String processing · 1/6

String processing

Text from people is messy. In this lesson you will clean it, check it and turn it into a neat report.

Prefer a video by a teacher? Find free videos on “python string methods split strip join tutorial” on YouTube ↗

In real life: Tidying a WhatsApp order list

Every morning customers send Ganesh orders on WhatsApp, typed in every possible way. He pastes the messages into one block of text. A few string methods clean each line, skip the empty ones and print a neat, aligned list for packing.

python
orders = """  ATTA   5
sugar 2

 Tea powder   1 """
for line in orders.splitlines():
    line = line.strip()
    if not line:
        continue
    parts = line.split()
    item = " ".join(parts[:-1]).title()
    qty = parts[-1]
    print(item.ljust(12, ".") + qty.rjust(3))
Atta, Sugar and Tea Powder, lined up with their quantities.

Practice (0/3 done)

Task 1 · Code · Python

Write clean_name(raw) that removes extra spaces (at the ends and between words) and gives each word a capital first letter. clean_name(" rAVI kumar ") returns "Ravi Kumar".

Task 2 · Code · Python

Write word_count(text) that returns a dict of how many times each word appears. Ignore capital letters and remove the punctuation marks . , ! ? first. word_count("Chai is hot. Chai is sweet!") returns {"chai": 2, "is": 2, "hot": 1, "sweet": 1}.

Task 3 · Code · Python

Write stock_report(items) where items is a list of (name, qty) pairs. Return ONE string with one line per item: the name padded with ljust(10), then the quantity padded with rjust(4). Join the lines with a new line, with no new line at the very end.

Quick quiz

Question 1

1.What is " Hi ".strip()?

Question 2

2.What is "a,b,,c".split(",")?

Question 3

3.Which of these is True?

Question 4

4.What is "7".zfill(3)?

Question 5

5.After s = " hi " and then s.strip() on its own line, what is s?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: List, dict and set comprehensions