livepython.net
CHAPTER 12Working With Strings
12.1  INDEX AND SLICE

Python String Indexing and Slicing

Get One Character with a String Index

A string is a row of characters, and every character has a position number called its index. Put the index in square brackets after the string to get that one character: name[0].

Think of it like the seats in a cinema row. Every seat has a number, so you can walk straight to seat 3 without checking the others.

PYTHONedit me
name = "Sunny"
print(name[0])
print(name[1])
print(name[4])
OUTPUT
S
u
y

It works exactly like the list indexes from chapter 9, because a string is a sequence too: a sequence of characters.

CharacterIndexNegative index
S0-5
u1-4
n2-3
n3-2
y4-1

The rules

  • The first character is at index 0, not 1.
  • The last character is at index len(name) - 1.
  • Negative indexes count from the end: -1 is the last character, -2 the one before it.
  • Spaces and punctuation are characters too, so they have an index like everything else.
PYTHONedit me
city = "New York"
print(city[-1])
print(city[4])
print(city[len(city) - 1])
OUTPUT
k
Y
k

city[4] is Y because the space at index 3 counts. And -1 is a short way to write len(city) - 1.

Avoid: an index past the end

PYTHONedit me
name = "Sunny"
print(name[5])
OUTPUT
IndexError: string index out of range

Don't be scared of this error! It's saying: "There's no character at that position." "Sunny" has 5 characters, so the last index is 4.

Common beginner doubt: "Why does counting start at 0?" Read the index as "how many steps from the start". The first character is 0 steps away, the second is 1 step away.

text[0] is the first character and text[-1] is the last.

your turnPredict the output

What will this print?

word = "Python" print(word[-2])
Your turn! What will this code show on the screen?
your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Slice a String: Take a Piece of Text

A slice takes a piece of a string. Write two indexes with a colon between them: text[start:stop]. You get the characters from start up to, but not including, stop.

Think of it like cutting a loaf of bread: you make one cut at start, another at stop, and take the part in between.

PYTHONedit me
word = "LivePython"
print(word[0:4])
print(word[4:10])
print(word[:4])
print(word[4:])
OUTPUT
Live
Python
Live
Python

Leave out start and the slice begins at the start. Leave out stop and it runs to the end. You did the same with lists in chapter 9.

The rules

You writeYou get
s[2:5]from index 2 up to, not including, 5
s[:3]the first 3 characters
s[3:]everything from index 3 to the end
s[-3:]the last 3 characters
s[::2]every second character
s[::-1]the whole string, backwards

The third number is the step: how far to jump each time. A step of -1 walks backwards, which is the classic way to reverse a string.

PYTHONedit me
message = "Hello Sunny"
print(message[-5:])
print(message[::2])
print(message[::-1])
OUTPUT
Sunny
HloSny
ynnuS olleH

Slices never crash

An index past the end gives an IndexError. A slice past the end doesn't: Python gives you whatever is there.

PYTHONedit me
code = "Hi"
print(code[0:50])
print(code[5:9])
print("end")
OUTPUT
Hi

end

code[5:9] is an empty string "", so print() shows an empty line.

Common beginner doubt: "Why isn't stop included?" Because then stop - start is the length of the slice: s[2:5] has exactly 3 characters. And s[:3] plus s[3:] gives back the whole string, with nothing lost and nothing doubled.

text[start:stop] takes the characters from start up to, not including, stop.

your turnFill the gap

Take the first three letters

word = "Sunshine" print(word?)

It should print: Sun

Which piece makes this code work?
your turnType the output

Type what this prints

s = "Python" print(s[::-1])
Read the code line by line, then type the output exactly.

Strings Are Immutable: You Can't Change One Letter

Strings are immutable: once a string is made, its characters can never change. You can read any character with an index, but you can't replace one.

Think of it like a printed name badge. You can't rub out one letter. If the name is wrong, you print a new badge.

Avoid: changing a character in place

PYTHONedit me
name = "Sunny"
name[0] = "B"
print(name)
OUTPUT
TypeError: 'str' object does not support item assignment

Every error is a clue! "Item assignment" means name[0] = …, and str objects (strings) don't allow it. This is a big difference from lists: in chapter 9 you changed nums[0] freely, because lists are mutable (changeable).

Good: build a new string

Make a new string out of slices and +, and store it in the same variable:

PYTHONedit me
name = "Sunny"
name = "B" + name[1:]
print(name)
OUTPUT
Bunny

name[1:] is "unny". Glue "B" in front, and you have a brand-new string. The old "Sunny" was never touched.

The rules

  • You can read characters and slices: name[0], name[1:].
  • You can't change, add or remove a character inside a string.
  • You can build a new string and store it, even in the same variable.
PYTHONedit me
word = "cat"
word = word[:2] + "r"
print(word)
greeting = "Hi"
greeting += "!"
print(greeting)
OUTPUT
car
Hi!

Common beginner doubt: "But I changed greeting with +=!" You changed the variable, not the string. greeting += "!" makes a new string "Hi!" and puts it in the variable, the same reassignment you learned in chapter 4.

Strings are immutable: build a new string instead of changing one character.

your turnFix the code

Fix the code so it prints: Rocky

It should print: Rocky

name = "Rocku"
name[4] = "y"
print(name)
This code does not work yet. Fix it, then press Run.
your turnPick the right idea

s holds "Hat". Which line makes s hold "Cat" without an error?

Think about it, then pick one.

Loop Over a String and Check with in

A string is a sequence, so a for loop from chapter 10 can walk through it one character at a time, from left to right.

Think of it like reading a word with your finger: you point at each letter in turn until you reach the end.

PYTHONedit me
for letter in "Lucky":
    print(letter)
OUTPUT
L
u
c
k
y

Each round of the loop, letter holds the next character. The loop stops by itself after the last one.

Counting characters

Put an if inside the loop, and you can count the characters you care about, like vowels:

PYTHONedit me
word = "education"
count = 0
for ch in word:
    if ch in "aeiou":
        count += 1
print("Vowels:", count)
OUTPUT
Vowels: 5

ch in "aeiou" is True when the character is one of those five letters.

in checks for a piece of text

in works with longer pieces too. It checks whether one string sits anywhere inside another, as a substring (a string inside a string):

PYTHONedit me
title = "LivePython"
print("Py" in title)
print("py" in title)
print("Python" not in title)
OUTPUT
True
False
False

The rules

  • for ch in text: gives you one character per round, left to right.
  • Spaces count as characters, so the loop visits them too.
  • "piece" in text is True when the text contains that piece anywhere.
  • in is case-sensitive, like ==: "py" is not "Py".

Common beginner doubt: "Do I need the index to loop over a string?" Usually not. for ch in text: is shorter and clearer. Use for i in range(len(text)): only when you need the position number too.

A for loop walks through a string one character at a time, and in checks if a piece is inside.

your turnPredict the output

What will this print?

count = 0 for ch in "banana": if ch == "a": count += 1 print(count)
Your turn! What will this code show on the screen?
your turnPredict the output

Remember list slices?

colors = ["red", "green", "blue"] print(colors[1:])
Your turn! What will this code show on the screen?

Practice: Index and slice

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 100.Python Program to Print the First and Last Character of a StringEasySolve
  2. 101.Python Program to Check if a String Is a PalindromeMediumSolve