String methods in Python: turn raw text into data
An order arrives as one line of text: TEE-SAGE-M,2,38.00. Product, color, size, quantity, and price are all in there. String methods are how you get them out.
The big idea
Strings have built-in methods such as split, strip, upper, and lower that each return a new, transformed string.
See it in code
split(",") cuts a string at every comma and returns the pieces as a list:
line = "TEE-SAGE-M,2,38.00"
parts = line.split(",")
print("Fields:", parts)
print("SKU:", parts[0])Fields: ['TEE-SAGE-M', '2', '38.00'] SKU: TEE-SAGE-M
The fields are still text. parts[1] is the string "2", not the number 2, so it has to be converted before any math.
Real data is messy. Leading and trailing spaces make an equality test fail even when the text looks right. strip() removes them:
raw = " TEE-SAGE-M "
product = raw.split("-")[0]
print("Is it a tee?", product == "TEE")
product = raw.strip().split("-")[0]
print("Is it a tee?", product == "TEE")Is it a tee? False Is it a tee? True
The first product was " TEE", spaces included, so it didn't equal "TEE". Methods chain left to right: strip first, then split the clean result.
Put it together. Split the line, convert the numbers, split the SKU again and unpack its three parts, then format a packing slip:
line = " TEE-CLAY-L,3,38.00 "
parts = line.strip().split(",")
sku = parts[0]
quantity = int(parts[1])
price = float(parts[2])
product, color, size = sku.split("-")
print(f"Order total: ${quantity * price:.2f}")
print(f"Packing slip: {quantity} x {color.title()} {product.lower()}, size {size}")Order total: $114.00 Packing slip: 3 x Clay tee, size L
sku.split("-") returned exactly three pieces, so they could be unpacked into three names at once. title() and lower() changed the display, not the data.
The same toolkit reads any structured text: the columns of a CSV file, a log line, a protein name in a database, the query string of a URL.
Try it yourself
Slice the SKU to get its category with sku[:3], and test membership with size in ["XS", "S", "M", "L", "XL"]. Then parse a second line, "PANTS-OAT-L,1,78.00", with the same code.
The common mistake
Expecting a method to change the original. line.strip() returns a new string and leaves line as it was. Strings are immutable, so keep the result: line = line.strip().
What it unlocks
The pieces you extract usually land in a list or a dictionary, and get displayed with f-strings.