Kodewick
Lesson 4 of 31Contents

Strings

Lesson 4 of 31 · Part 1 · Basics · about 15 minutes

A string is a piece of text: a name, a sign on a house, a whole letter. You have printed strings since lesson 1. Now you will take them apart and put them together.

Joining and repeating

+ joins two strings end to end. * repeats a string a number of times.

main.py
1first = "Lamp"2second = "lighter"3print(first + second)4print(first + " " + second)5print("-" * 20)6print("ha" * 3)
Output
Lamplighter
Lamp lighter
--------------------
hahaha

+ adds no space of its own; you add one yourself, as in the second line. Both sides of + must be strings: "Lamp " + 3 is a TypeError, so write "Lamp " + str(3) or use an f-string.

How long is it?

len() counts the characters in a string. Spaces and punctuation count too.

main.py
1word = "lamplighter"2print(len(word))3print(len("Hi there!"))4print(len(""))
Output
11
9
0

"" is the empty string: a string with nothing in it, length 0.

One character at a time

Each character has a position, called its index. Counting starts at 0. Negative numbers count from the end: -1 is the last character.

CharacterWick
Index0123
From the end-4-3-2-1
main.py
1name = "Wick"2print(name[0])3print(name[3])4print(name[-1])5print(name[4])
Output
W
k
k
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print(name[4])
IndexError: string index out of range

"Wick" has 4 characters, so the last index is 3. Asking for name[4] is an IndexError. To get the last character of any string, [-1] is easier than working out the length.

Slicing

text[start:stop] takes a piece of a string: from start up to, but not including, stop. Leave out start to begin at the front; leave out stop to go to the end.

main.py
1word = "lamplighter"2print(word[0:4])3print(word[4:9])4print(word[:4])5print(word[4:])6print(word[-3:])
Output
lamp
light
lamp
lighter
ter

A handy way to think of it: the numbers point at the gaps between characters. [0:4] cuts at gap 0 and gap 4, which leaves 4 characters. And word[:4] + word[4:] always gives back the whole word.

Guess first

What does this print?

1word = "sunrise"2print(word[1:4])

Unlike a single index, a slice never gives an error. If it runs past the end, you simply get less, or an empty string.

Steps and reversing

A third number sets the step: [::2] takes every second character. A step of -1 walks backwards, which reverses the string.

main.py
1digits = "0123456789"2print(digits[::2])3print(digits[1::2])4print("stressed"[::-1])
Output
02468
13579
desserts

[::-1] is the usual Python way to reverse a string. Read it as "the whole thing, backwards".

Strings can't be changed

You can read any character of a string, but you cannot replace one in place:

main.py
1name = "Wick"2name[0] = "N"
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    name[0] = "N"
TypeError: 'str' object does not support item assignment

Strings are immutable: once made, they stay as they are. To "change" one, build a new string from pieces and store it under the same name:

main.py
1name = "Wick"2name = "N" + name[1:]3print(name)
Output
Nick

Special characters and long text

The backslash codes from lesson 1 work in every string: \n for a new line, \t for a tab, \" for a quote. A \n counts as one character. For text that spans several lines, three quotes are easier: everything up to the closing three quotes is kept, line breaks and spaces included.

main.py
1print(len("a\nb"))2sign = """Lamp Street3  No. 7"""4print(sign)
Output
3
Lamp Street
  No. 7

Tip: Strings in triple quotes are also how Python programmers write longer notes at the top of a program. You will see them again with functions.

Practice

Write the code, then press Check. A hint costs nothing; the answer is there when you need it.

Exercise 1

Initials

Use indexing to print the initials of first and last, each followed by a period.

It should print
A.L.
exercise1.py
1first = "Ada"2last = "Lovelace"3print(first, last)
Output
Press Run or Ctrl+Enter
Exercise 2

Backwards

Print word reversed. You get a different word.

It should print
reward
exercise2.py
1word = "drawer"2print(word)
Output
Press Run or Ctrl+Enter
Exercise 3

Card ending

Show only the last four digits of the card number, in the sentence below.

It should print
Card ending in 3316
exercise3.py
1card = "4921 7734 0058 3316"2print("Card ending in", card)
Output
Press Run or Ctrl+Enter

What you learned

  • + joins strings, * repeats them; numbers must be converted first.
  • len() counts characters; "" is the empty string.
  • text[0] is the first character, text[-1] the last; past the end is an IndexError.
  • text[start:stop] slices up to but not including stop; either end can be left out.
  • text[::-1] reverses a string.
  • Strings are immutable: build a new one instead of changing a character.
  • Triple quotes make a string that spans several lines.