Codiqo

Learn Python · lesson 6 of 60 · about 7 minutes

Slicing and String Methods

Text copied from other apps arrives messy. Read single characters, cut out parts, and tidy text with built-in methods.

What you'll learn

  • Count characters with len()
  • Read characters by index
  • Slice part of a string
  • Use upper(), lower(), title(), strip() and replace()

Messy text

You copy today's job from a notes app, and it arrives as " WATER THE PLANTS ": in capitals, with spaces at both ends. Your assistant should say *Today: water the plants*. To get there, you need to read and change text.

Positions start at 0

len(text) counts the characters. Each character has a position, its index, counting from 0: text[0] is the first one, and text[-1] is the last. A slice text[start:end] cuts out a piece, stopping just before end. Leave a side out to go to the start or the end.

len, indexes and slices

job = "plants"
print(len(job))
print(job[0], job[-1])
print(job[0:4])
print(job[2:])

Output

6
p s
plan
ants

String methods

| Method | Does |
|---|---|
| upper() | ALL CAPS |
| lower() | all lowercase |
| title() | Capitals At The Start Of Each Word |
| strip() | Removes spaces from both ends |
| replace(a, b) | Swaps every a for b |

A method gives back a new string. The text you called it on never changes, so use the result or store it.

Tidying the job from the notes app

task = "  WATER THE PLANTS  "
print(task.strip().lower())
print(task.strip().title())
print(task.replace("PLANTS", "GARDEN").strip())

Output

water the plants
Water The Plants
WATER THE GARDEN

Tip

task.strip() on a line of its own does nothing useful: the tidy copy is made and thrown away. Write task = task.strip(), or use the method where you print.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.