Intermediate · Working with data · topic 28 of 50 · 20 min
String processing
Explanation
Cleaning messy input
raw = " rAVI kumar "
print(raw.strip())
print(" ".join(raw.split()).title())
phone = " 98765 43210 "
print(phone.replace(" ", ""))| Method | What it does | Example 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 / endswith | checks the start or end | "INV-7".startswith("INV") |
| isdigit / isalpha | only digits? only letters? | "560001".isdigit() → True |
| zfill(n) / ljust(n) / rjust(n) | pads to a width | "7".zfill(3) → "007" |
Splitting lines and words
notes = """Rice 5 kg
Dal 2 kg
Oil 1 litre"""
lines = notes.splitlines()
print(lines)
print("Oil 1 litre".split())
print("a b".split(" "))Counting words
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)Checking what text contains
print("560001".isdigit())
print("Asha".isalpha())
print("Asha Rao".isalpha())
print("-5".isdigit(), "2.5".isdigit(), "".isdigit())Padding and building reports
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)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
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.
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))Practice (0/3 done)
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".
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}.
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
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.