Python, lesson 8
Text is everywhere: names, commands, log lines, CSV files. Python's str type comes with a
large toolbox of methods. Strings are immutable, so every method returns a new string
and leaves the original alone. If you want to keep the result, assign it.
A string is a sequence of characters, so indexing and slicing work just like lists:
split() turns one string into a list; join() does the reverse. Note that join is called
on the separator:
replace(old, new) swaps every occurrence of a piece of text, and lower() or
help you compare text without worrying about capital letters.
2 exercises to try what you just read.
casefold()f-strings accept a format spec after a colon. A number sets the width, and <, > or ^
aligns the text left, right or centre inside it:
That's all you need to line up a table. Strings also support * for repetition, so
"-" * 20 draws a line.
The second exercise below is a small project. It uses input reading (lesson 3), a loop (lesson 5), a function (lesson 6), a list (lesson 7) and string formatting from this lesson. Plan it before you type:
Breaking a task into small steps like this is the most useful programming skill there is.
A palindrome reads the same forwards and backwards once you ignore case, spaces and
punctuation (keep only letters and digits). Read one line and print yes if it is a
palindrome, otherwise no. An empty line counts as a palindrome.
Sample input:
Sample output:
Each input line describes one item as name quantity price, where the name is one word, the
quantity is a whole number and the price is a decimal. Print a receipt:
x and the quantity
left-aligned in 4 characters, then the line total right-aligned in 8 characters with two
decimals.TOTAL left-aligned in 15 characters followed by the grand total right-aligned in 8
characters with two decimals.Sample input:
Sample output:
name = " ada lovelace "
clean = name.strip() # "ada lovelace"
print(clean.title()) # Ada Lovelace
print(clean.upper()) # ADA LOVELACE
print(name) # unchanged, spaces and allword = "Python"
print(word[0]) # P
print(word[-1]) # n
print(word[1:4]) # yth (start included, stop excluded)
print(word[::-1]) # nohtyP (a step of -1 walks backwards)email = "sam@example.com"
print("@" in email) # True
print(email.find("@")) # 3 (-1 if not found)
print(email.endswith(".com")) # True
print(email.count("m")) # 2
print("42".isdigit()) # Trueparts = "red,green,blue".split(",") # ['red', 'green', 'blue']
print(" | ".join(parts)) # red | green | blueprint(f"{'Tea':<8}|") # Tea |
print(f"{'Tea':>8}|") # Tea|
print(f"{3.5:>8.2f}|") # 3.50|
print(f"{1234567:,}") # 1,234,567Never odd or even!yescoffee 2 3.20
bagel 1 2.75coffee x2 6.40
bagel x1 2.75
-----------------------
TOTAL 9.15