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
On this page
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
Built-in functions: the tools on the wall
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.
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.
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
| Function | Remember |
|---|---|
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 / max | key= decides what is compared; default= is returned for an empty input instead of a ValueError. |
sum(xs, start=0) | Adds everything to start. |
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
450all([]) 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.
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."
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?"
Scenario"A job computes max(latencies) and crashes on quiet days. Fix it."
Trap"sorted() and list.sort() are interchangeable."
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 readFiles, JSON, CSV and dates
Read files line by line, JSON and CSV, ISO dates, strptime codes, time zones and zoneinfo.
Related lessons
Dict, set and list methodsPython for data engineers · 5 min read
ComprehensionsPython for data engineers · 5 min read
Sorting with key functions
Previous: Dict, set and list methods
Primary sources: Built-in functions · String methods · Format specification