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.
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):
...
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.