String methods

Strings come with built-in operations called methods. You call a method with a dot after the value: item.upper(). The parentheses are required even when there is nothing to pass.

item = "Sourdough Bread"
print(item.upper())
print(item.lower())
print(item)

The last line shows the original is unchanged. Strings cannot be modified; every method returns a new string. If you want to keep the result, name it: item = item.lower().

The methods you will use most

item = "  bread  "
print(item.strip())

strip removes spaces from both ends, and other blank characters such as tabs and line breaks. Useful for cleaning up what people type.

item = "sourdough bread"
print(item.replace("bread", "loaf"))
print(item.count("o"))
print(item.find("bread"))
print(item.find("milk"))

replace swaps every occurrence. count counts them. find gives the position of the first match, or -1 if there is none.

code = "SKU-1042"
print(code.startswith("SKU"))
print(code.endswith("42"))

startswith and endswith return booleans, so they slot into if directly.

Building text from values

Earlier you built text with + and str(). An f-string is easier: put f before the opening quote, and write names or expressions inside curly braces.

item = "bread"
quantity = 3
price = 40
print(f"{quantity} x {item} = {quantity * price}")

Anything inside {} is evaluated and converted to text for you. This is the way to build output from now on.

Controlling how numbers look

A price of 2.5 should print as 2.50, and a column of prices should line up. A format spec after a colon inside the braces does this:

price = 2.5
print(f"{price:.2f}")
print(f"{1250:,}")
print(f"{0.256:.1%}")

.2f means "a decimal number with 2 digits after the point". , puts thousands separators in. .1% multiplies by a hundred and adds the sign. They combine: {1250.5:,.2f} gives 1,250.50.

A number before the type sets a minimum width, and <, > or ^ push the value to the left, right or centre of it. That is how you line up columns:

items = ["apple", "bread", "milk"]
prices = [40, 25, 2.5]
for i in range(3):
    print(f"{items[i]:<8}{prices[i]:>8.2f}")

{items[i]:<8} is the item padded with spaces to 8 characters, left aligned; {prices[i]:>8.2f} is the price with two decimals, right aligned in 8 characters. You will not remember all of these. Remember that .2f exists and that the colon is where the rest goes.

Splitting text into pieces

split() breaks a string into a list of pieces wherever there is blank space, treating any run of spaces as one break. Give it a separator, like split("-"), to break at that character instead. join puts pieces back together with a separator. Lists are the subject of the next module, so for now just see what they look like:

line = "apple  bread milk"
print(line.split())
print("BRD-001-A".split("-"))
print("-".join(["apple", "bread"]))

Try it

Normalise an item name

Item names typed by staff are messy: extra spaces at the ends, random capitals. Write normalise(name) that returns the name with the spaces at both ends removed and everything in lowercase.

normalise("  Sourdough Bread ")  ->  "sourdough bread"
normalise("MILK")                ->  "milk"
def normalise(name):
    ...

Receipt line with an f-string

Write receipt_line(item, quantity, price) that returns one line of a receipt in exactly this format, where the last number is quantity times price:

receipt_line("bread", 3, 40)   ->  "3 x bread = 120"
receipt_line("milk", 2, 2.5)   ->  "2 x milk = 5.0"

The total is written the way Python prints it, so 2 * 2.5 appears as 5.0, not 5.

def receipt_line(item, quantity, price):
    ...

Money format

Write money(amount) that returns the amount as text with exactly two decimal places and commas separating thousands.

money(2.5)     ->  "2.50"
money(40)      ->  "40.00"
money(1250)    ->  "1,250.00"
money(1234567.891)  ->  "1,234,567.89"

The point is to practise format specs inside an f-string.

def money(amount):
    ...

Has the prefix?

Every bakery product code starts with BRD-. Write is_bakery(code) that returns True if code starts with that prefix and False otherwise.

is_bakery("BRD-001")  ->  True
is_bakery("MLK-010")  ->  False
def is_bakery(code):
    ...

Next: Lists.