All lessons

Strings & booleans · step 6 of 22

String methods & slicing

10 minClean text up, pull pieces out of it, and search for patterns.

Methods return a copy

Strings come with built-in tools called methods. Call them with a dot. None of them change the original — they hand you a new string.

name = "  ada lovelace  "
print(name.strip())            # "ada lovelace"
print(name.strip().title())    # "Ada Lovelace"
print("HELLO".lower())         # "hello"
print("python".replace("p", "P"))   # "Python"

The ones you will use most: .upper(), .lower(), .strip(), .title(), .replace(old, new) and .split() (which breaks a sentence into a list of words).

Slicing takes a piece

Every character has a position number, starting at 0.

word = "Python"
print(word[0])      # P
print(word[-1])     # n  — counting from the end
print(word[0:3])    # Pyt — positions 0, 1, 2; the stop value is not included
print(word[3:])     # hon — from 3 to the end

Finding patterns with regex

When you need to find a pattern rather than exact text, Python has the re module. re.findall(r"\d+", "I have 3 cats") returns ['3'], because \d+ means "one or more digits".

Remember this

  • .upper(), .lower(), .strip(), .replace() return a new string
  • Indexing starts at 0 and negative indexes count from the end
  • Slicing is [start:stop], and the stop value is not included

Quick quiz

Three questions. 3 correct answers and you have the idea — you can retry as often as you like.

  1. 1. What does "Python"[0] give?

  2. 2. What is " hi ".strip()?

  3. 3. word = "Python" — what is word[1:4]?

Answer all three to check them.

Now write it yourself

0/3 passed
1

Practice 1

Clean up the messy name and print it in title case.

practice_1.py

Given for you

name = "  ada LOVELACE  "
2

Practice 2

Print the first three letters of `word`, then its last two letters, each on its own line.

practice_2.py

Given for you

word = "Python"
3

Practice 3

Import re and print every number found in the sentence — the output should look like ['3', '12']

practice_3.py

Given for you

text = "We shipped 3 lessons and 12 labs"

Finish with two of three quiz answers correct and every exercise passing, and this lesson is marked complete.