Learn/Python/8. Strings and a small project
Lesson 8 of 15
Sign in

Python, lesson 8

Strings and a small project

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.

Indexing and slicing

A string is a sequence of characters, so indexing and slicing work just like lists:

Searching and testing

Splitting and joining

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.

Exercise 1

Palindrome checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Receipt printer

Press Ctrl Enter or Check to test your code.

casefold()

Formatting for columns

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.

Project: putting it together

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:

  1. Read lines until the input ends.
  2. Split each line into a name, a quantity and a unit price.
  3. Work out each line total and keep a running sum.
  4. Format every row to fixed widths, then print the total.

Breaking a task into small steps like this is the most useful programming skill there is.

Further reading

  • String methods
  • Format specification mini-language
  • The Python Tutorial: Fancier output formatting

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:

  • One row per item: the name left-aligned in 10 characters, then x and the quantity left-aligned in 4 characters, then the line total right-aligned in 8 characters with two decimals.
  • Then a line of 23 dashes (the width of a row).
  • Then 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 all
word = "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())             # True
parts = "red,green,blue".split(",")   # ['red', 'green', 'blue']
print(" | ".join(parts))              # red | green | blue
print(f"{'Tea':<8}|")       # Tea     |
print(f"{'Tea':>8}|")       #      Tea|
print(f"{3.5:>8.2f}|")      #     3.50|
print(f"{1234567:,}")       # 1,234,567
Never odd or even!
yes
coffee 2 3.20
bagel 1 2.75
coffee    x2       6.40
bagel     x1       2.75
-----------------------
TOTAL              9.15