Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Programming · Python · Chapter 06 / 16

Programming learning path

Strings & text formatting

String methods, f-strings, splitting/joining and an introduction to regular expressions.

Common string methods

Strings are immutable, so no string method ever modifies the original in place.

Strings are immutable, so no string method ever modifies the original in place — but that does not mean every method returns a new string. Methods that transform text, like .upper(), .lower(), .strip(), and .replace(old, new), return a new string; query methods like .startswith(prefix), .endswith(suffix), .find(sub), or .count(sub) instead return a bool or an int, not text at all. .strip() (and .lstrip()/.rstrip()) removes leading/trailing whitespace by default, or any characters you specify. in checks substring containment directly ("cat" in "concatenate" is True), and .find(sub) returns the index of the first match or -1 if not found, while .index(sub) does the same but raises ValueError instead of returning -1.

Key points

  • String methods never modify the original; text-transforming methods return a new string, while query methods like .find() or .startswith() return a bool or int
  • in checks substring containment; .find() returns -1 if missing, .index() raises
  • .strip()/.lstrip()/.rstrip() remove whitespace or specified characters from the edges

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Cleaning up whitespace, changing case, replacing a substring and checking containment.

Common pitfalls

  • raw.strip() does not change raw itself — you must reassign the result
  • "Hello".index("z") raises ValueError; use .find() if a missing substring shouldn't crash the program

Practice exercise

Write clean_username(text) that strips whitespace, lowercases the result, and replaces any spaces in the middle with underscores.

f-strings for readable formatting

The modern, preferred way to build strings with embedded values, prefixed with f and using {expression}.

An f-string, written f"...", evaluates any Python expression placed inside {} directly where it appears in the string, converting it to text automatically — including method calls and arithmetic, not just plain variable names. A colon after the expression introduces an optional format spec for controlling decimal places, padding, alignment and thousands separators, such as f"{price:.2f}" for exactly two decimal places or f"{count:,}" for a thousands separator. f-strings are evaluated once, at the point they run, so they always reflect the current value of any variable they reference.

Key points

  • f"{expr}" evaluates any expression, not just a plain variable name
  • A format spec after a colon controls decimals, padding and thousands separators
  • f-strings are evaluated at the moment they run, always showing the current value

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

An f-string with a format spec for currency, and another showing a method call and arithmetic inline.

Common pitfalls

  • Forgetting the f prefix turns "{name}" into a literal, unevaluated string with braces in it
  • f"{value:.2f}" on a non-numeric value raises a ValueError at runtime

Practice exercise

Given a list of (product, price, quantity) tuples, print a receipt line for each with the product name, right-aligned price to 2 decimals, and the line total.

Splitting and joining strings

split() turns text into a list; join() turns a list back into text — the two are inverses of each other.

text.split(sep) breaks a string into a list of pieces at every occurrence of sep, or on any run of whitespace if sep is omitted entirely. sep.join(list_of_strings) does the reverse: it stitches a list of strings together, placing sep between each pair, and is called on the separator itself, not on the list — a detail that trips up many beginners the first time. split() and join() are close inverses for a simple case like ",".join(line.split(",")), but they are not general inverses: whitespace-splitting with no argument collapses repeated separators, and any change to the number of pieces breaks a clean round-trip. This split/transform/join pattern is one of the most common ways to process simple, well-behaved delimiter-separated text — but real CSV data, where a field can itself contain a comma or a quote, needs the dedicated csv module covered later instead.

Key points

  • text.split(sep) breaks a string into a list; .split() with no argument splits on any whitespace
  • sep.join(list) is called on the separator string, not on the list
  • split then transform then join suits simple, well-behaved delimited text — not real CSV parsing

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Splitting a CSV-style line into named variables, then rejoining with a different separator.

Common pitfalls

  • list.join(sep) is backwards — Python has sep.join(list), called on the separator
  • line.split(",") on a line with the wrong number of commas raises ValueError when unpacked into a fixed number of names

Practice exercise

Write delimited_rows_to_dicts(lines, headers) for a deliberately simple format where commas are guaranteed not to appear inside a field: split each line on commas and zip it with headers to build a list of dictionaries, one per line.

An introduction to regular expressions

Pattern matching for text that's too flexible for plain split()/in checks, using the re module.

The re module matches text against a pattern rather than a fixed literal string: \d matches a digit, \w matches a word character, + means "one or more", * means "zero or more", and . matches any character except a newline by default (the re.DOTALL flag changes that), among many other pattern elements. For a normal Unicode str pattern, \d and \w match Unicode digits and word characters, not just the ASCII 0-9/letters-and-underscore ranges — the re.ASCII flag restricts them to ASCII when that is specifically what you need. re.search(pattern, text) finds the first match anywhere in the string and returns a Match object (or None), while re.findall(pattern, text) returns every match as a list, and re.sub(pattern, replacement, text) replaces every match. Regular expressions are reached for once plain string methods like .split() and in cannot express the needed flexibility.

Key points

  • . matches any character except newline by default; \d and \w are Unicode-aware unless re.ASCII is used
  • re.search finds the first match, re.findall returns all matches as a list
  • re.sub replaces every match with a given replacement

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Finding every phone number in a string, then masking each one, using the same pattern.

Common pitfalls

  • Forgetting the r prefix (raw string) on a pattern with backslashes causes confusing double-escaping bugs
  • Reaching for regex when a plain .split() or in check would be simpler and faster overcomplicates the code

Practice exercise

Use the pattern \w+@\w+\.\w+ with re.findall to extract email-like strings from a block of text, then identify at least three valid-looking addresses (with a dot, hyphen, or +tag) that it misses, and explain in one sentence why production email validation should not be reduced to this toy regex.

Source registry

3 chapter references
The Python Standard Library

Authoritative behavior for built-in types and standard library modules

Python Software Foundation · Official reference
Source ↗
The Python Tutorial

Baseline syntax, control flow, functions and module basics

Python Software Foundation · Official documentation
Source ↗
What's new in Python 3.14

Current-version language and runtime changes, including template strings and free-threading support

Python Software Foundation · Release notes
Source ↗