Skip to content
Bronze 6 min read · Basics 2 practice problems ↓

Strings and built-in functions

Data arrives as text, and pipelines turn it into records with a handful of string methods and built-in functions. This lesson covers the ones you will use daily (split, join, strip, f-strings, zip, enumerate, min, max, sorted) and the behaviours that surprise people: strip removing characters rather than a word, zip silently dropping items, all() being true on nothing, and sort() returning None.

Foundations · Python for data engineers · Bronze · Python basics for data engineers, lesson 2 of 3

In plain words first

String methodsmethod: A function defined inside a class and called on an object, like name.upper() or order.total(). Learn more →: a label maker

Cut a line into fields, trim the edges, swap a word, stick pieces together. Each gives you a new label; the old one is never changed.

Built-in functions: the tools on the wall

zip, enumerate, min, max, sum and sorted are always there, no import needed, and they work on any iterableiterable: Anything you can loop over with for: a list, a string, a dict, a range, a file. Calling iter() on it gives a fresh iterator. Learn more →.

Raw data arrives as text: log lines, CSV fields, file names. Cleaning it is mostly string methods, and putting it together is mostly built-in functions. Each has one or two behaviours that look like bugs until you know them.

split, join and strip

split(sep) cuts at every separator and keeps empty fields, which matters for CSV-like data where ,, means a missing value. split() with no argument is different: it splits on any run of spaces, tabs and newlines and never returns empty strings. sep.join(items) is the reverse, and every item must already be a string.

strip, lstrip and rstrip remove characters, not a word: rstrip(".csv") keeps removing any of ., c, s, v from the right. To remove an exact prefix or suffix, use removeprefix / removesuffix.

Python · cutting, trimming and gluing text
line = "  asha,  Pune ,,42  "
print(line.split(","))  # with a separator: every field kept, even empty ones
print("a  b\tc\n".split())  # no separator: any run of spaces, tabs or newlines
print(repr(line.strip()))  # both ends
print("xxhubxx".strip("x"), "|", "pos.csv".rstrip(".csv"))  # a SET of characters!
print("pos.csv".removesuffix(".csv"))  # removes exactly this text, once

print("-".join(["2026", "03", "01"]))
try:
    print(",".join(["id", 7]))
except TypeError:
    print("join needs strings")
print(",".join(map(str, ["id", 7])))

Output from a real run

['  asha', '  Pune ', '', '42  ']
['a', 'b', 'c']
'asha,  Pune ,,42'
hub | po
pos
2026-03-01
join needs strings
id,7

replace, startswith and f-strings

replace(old, new) swaps every occurrence. startswith and endswith accept a tupletuple: An ordered, immutable sequence like ("Pune", 2026). Because it cannot change, it can be a dict key; use it for small fixed records. Learn more → to test several options at once. In an f-string, the part after : is a format spec: >8 right-aligns in 8 characters, <8 left-aligns, ,.2f adds thousands separators and 2 decimals, .1% shows a fraction as a percentage, 03d pads a whole number with zeros.

Python · renaming paths and formatting a report line
path = "raw/2026/orders_01.csv"
print(path.replace("raw/", "clean/"))
print(path.startswith(("raw/", "landing/")), path.endswith((".csv", ".json")))

fare, share, rider = 1234.5, 0.0712, "asha"
print(f"[{rider:>8}] [{rider:<8}] [{fare:,.2f}] [{share:.1%}] [{7:03d}]")
print(f"{fare=}")  # the name and the value, handy when debugging

Output from a real run

clean/2026/orders_01.csv
True True
[    asha] [asha    ] [1,234.50] [7.1%] [007]
fare=1234.5

zip, enumerate, any, all, min, max and sum

FunctionRemember
zip(a, b)Pairs items up and stops at the shortest input; strict=True raises instead.
enumerate(xs, start=1)Gives (position, item) pairs; start sets the first number.
any(xs) / all(xs)Is any item true / are all items true? On an empty input: False / True.
min / maxkey= decides what is compared; default= is returned for an empty input instead of a ValueError.
sum(xs, start=0)Adds everything to start.
Python · pairing, numbering and summarising
names = ["asha", "ben", "chitra"]
cities = ["Pune", "Goa"]
print(list(zip(names, cities)))  # stops at the shortest: chitra is dropped
try:
    list(zip(names, cities, strict=True))
except ValueError as e:
    print("strict=True:", e)

for rank, name in enumerate(names, start=1):
    print(rank, name)

print(any([]), all([]))  # no true item / no false item
fares = [120, 80, 200]
print(min(fares), max(names, key=len), max([], default=None))
print(sum(fares, start=50))  # start: 50 is added to the total

Output from a real run

[('asha', 'Pune'), ('ben', 'Goa')]
strict=True: zip() argument 2 is shorter than argument 1
1 asha
2 ben
3 chitra
False True
80 chitra None
450

all([]) is True because there is no item that fails. That is logically right but can hide a bug: "all rows are valid" is also true when there are no rows. Check for empty input separately when it matters.

map, filter, sorted and list.sort

map and filter are fine with one existing function, like map(int, xs). As soon as you need a lambda, or both transform and filter, a comprehensioncomprehension: A one-line way to build a list, set or dict from another iterable, like [x * 2 for x in xs if x > 0]. Learn more → reads better. sorted(xs) returns a new list; xs.sort() sorts the list itself and returns None.

Python · comprehensions versus map and filter, and the None from sort
fares = ["120", "80", "200"]
print(list(map(int, fares)))  # fine when it is one existing function
print([int(f) for f in fares if int(f) > 100])  # transform and filter: clearer
print(list(filter(None, ["a", "", None, "b"])))  # None: keep the truthy items

nums = [3, 1, 2]
print(sorted(nums), nums)  # a new sorted list; nums is unchanged
result = nums.sort()  # sorts nums itself...
print(result, nums)  # ...and returns None

Output from a real run

[120, 80, 200]
[120, 200]
['a', 'b']
[1, 2, 3] [3, 1, 2]
None [1, 2, 3]

Common mistakes

  • strip(".csv") to remove a file extension — strip removes any of those characters from the ends, so "pos.csv" becomes "po". Use removesuffix(".csv").
  • zip on lists that should be the same length — zip stops at the shortest and drops the rest without a word. Pass strict=True to get a ValueError.
  • xs = xs.sort() — sort works in place and returns None, so xs becomes None. Call xs.sort() alone, or use xs = sorted(xs).
  • max(values) on data that can be empty — It raises ValueError on an empty input. Pass default=None, or check first.

Key takeaways

  • split(sep) keeps empty fields; split() splits on any whitespace and drops them.
  • join needs strings: convert with map(str, items) first.
  • startswith and endswith take a tuple of options.
  • f-string format specs align, round and add separators: f"{x:,.2f}".
  • any([]) is False and all([]) is True.

Interview prep

THE QUESTION

"Clean a list of raw email strings and count how many distinct, valid ones there are."

I would strip each value and lowercase it, skip the ones that are empty after stripping, and put the rest in a set comprehension so duplicates collapse: len({e.strip().lower() for e in raw if e.strip()}). If "valid" means more than non-empty, I would add the rule as a small function in the filter, such as one "@" with text on both sides. Cleaning before deduplicating matters: "Asha@x.com" and "asha@x.com " are the same address.

Avoid: "strip removes a substring". It removes any of the given characters from the ends, which is why removesuffix exists.

Follow-ups · answer out loud, then open

Follow-up"Two lists should line up row by row. How do you pair them safely?"
zip(a, b, strict=True). Plain zip stops at the shorter list and silently drops the rest; strict makes a length mismatch a ValueError, which is what I want in a pipeline.
Scenario"A job computes max(latencies) and crashes on quiet days. Fix it."
On a day with no data the list is empty and max raises ValueError. I pass default=None and handle None downstream, or skip the metric for that day, and I filter out None values before taking the max if the data can contain them.
Trap"sorted() and list.sort() are interchangeable."
sorted returns a new list and works on any iterable; list.sort sorts in place and returns None, so writing xs = xs.sort() replaces the list with None.

Check yourself

4 questions

"a,,b".split(",") is...

Show the answer

["a", "", "b"]. With a separator, the empty field between the commas is kept.

"pos.csv".rstrip(".csv") returns...

Show the answer

"po". rstrip removes the characters . c s v from the right until it meets o.

list(zip([1, 2, 3], ["a", "b"])) has how many pairs?

Show the answer

2. zip stops at the shortest input.

nums = [3, 1]; print(nums.sort()) prints...

Show the answer

None. sort works in place and returns None.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · Python basics for data engineers · lesson 3 of 3 · 8 min read
Files, JSON, CSV and dates
Read files line by line, JSON and CSV, ISO dates, strptime codes, time zones and zoneinfo.

Related lessons

Previous: Dict, set and list methods

Primary sources: Built-in functions · String methods · Format specification