Skip to content
Lesson 3 of 10 · Python for Complete Beginners

Working with strings

Index, slice and clean text, build it with f-strings, and use the common string methods.

17 min

A string is a sequence of characters. Each character has a position, an index, and the first one is 0.

python5 lines
word = "python"
print(word[0])     # p
print(word[5])     # n
print(word[-1])    # n  (negative counts from the end)
print(len(word))   # 6

word[start:stop] takes the characters from start up to, but not including, stop. Leave one out to go to the end:

python4 lines
word[0:2]   # 'py'
word[2:]    # 'thon'
word[:3]    # 'pyt'
word[::-1]  # 'nohtyp'  (step -1 reverses)

MethodDoes
s.upper(), s.lower()change case
s.strip()remove spaces at both ends
s.split()break on whitespace into a list of words
s.replace("a", "b")swap every a for b
s.startswith("py")True or False
s.find("th")index of the first match, or -1

Put an f before the quotes and write any expression inside {}:

python3 lines
name = "Ada"
score = 92.5
print(f"{name} scored {score:.1f}%")   # Ada scored 92.5%

:.1f means one decimal place. f-strings are the clearest way to mix text and values.

Common misconception

“`word.upper()` changes `word`.”

The name sounds like an action on the string, and in many languages a method changes the object.

What is actually true

Strings can never be changed. Every method returns a new string and leaves the original alone. To keep the result, store it: word = word.upper().

How to catch yourself

If a string method seems to do nothing, you probably forgot to use or save its return value.

Steps
0/4

Build a tidy greeting from messy input, one step at a time.

  1. Start with the raw text

    Imagine the user typed " aDa loVElace ": extra spaces and odd capitals.

  2. Strip, then fix the case

    raw.strip().title() gives "Ada Lovelace". Methods chain left to right, each working on the result of the one before.

  3. Take the first word

    clean.split()[0] splits into ["Ada", "Lovelace"] and takes index 0.

  4. Write it with an f-string

    print(f"Welcome, {first}!") prints Welcome, Ada!.

Exercise4 checks
python

Write initials(full_name) that returns the initials of a name, each followed by a full stop, in capitals.

initials("Ada Lovelace") is "A.L.". Extra spaces and lowercase must not matter.

Your code must satisfy

  • initials("Ada Lovelace")→"A.L."two names
  • initials("grace brewster hopper")→"G.B.H."three names
  • initials(" alan turing ")→"A.T."extra spaces
  • initials("Plato")→"P."one name
starter code2 lines
def initials(full_name):
    pass
Exercise2 cases
python

Read one line of text. Print it in capitals, then on the next line print how many characters it has, like this:

code2 lines
HELLO THERE
11 characters

Your code must satisfy

  • two words
  • one word
starter code1 line
text = input()
  • Indexes start at 0, and negative indexes count from the end.
  • s[a:b] includes a and excludes b.
  • String methods return new strings: store the result if you want it.
  • f-strings (f"{value}") are the cleanest way to put values inside text.
Check yourself

Quick checks on strings.

1Multiple choice

What is "python"[1:4]?

  • A`"pyt"`
  • B`"yth"`
  • C`"ytho"`
  • D`"tho"`
2Multiple choice

What is "banana".replace("a", "o")?

  • A`"bonono"`
  • B`"bonana"`
  • C`"banono"`
  • D`"banana"`
3Numeric answer

What is len("hello world")?

4Fill the blanks

To get the last character of s, write s[].

Capitalisation, spacing and punctuation are ignored when grading.

5Multiple choice

After s = "hi" and s.upper() on its own line, what is s?

  • A`"HI"`
  • B`"hi"`
  • CNone
  • DAn error
For you · never graded

Pick a short message you sent today. What would you use `.split()`, `.lower()` or slicing for if a program had to read it?

Practise this lesson, not just read it

In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Python for Complete Beginners is planned around your week. Free.