Skip to contentSkip to navigation

Module 03 · Lesson 03

Strings & Text Representation

Work with text as a sequence of characters: write strings in single, double or triple quotes, index and slice them, join and repeat them, and understand why they cannot be changed in place.

  • About 8 minutes
  • Beginner friendly
  • 12-question quiz at the end

What you will learn

  • Index and slice text
  • Join and repeat
  • Loop over letters
  • Make a secret code

Text is a row of characters

A string is text in quotes. Python sees it as characters in a row, so lots of list tricks work on it too.

  • Quotes

    "hi" and 'hi' are the same. Pick the one that does not clash with the text.

  • Index and slice

    word[0] is the first character, word[-1] the last and word[1:3] a piece.

  • Fixed

    You cannot change one letter in place. You build a new string instead.

  • Join and repeat

    + joins text, * repeats it and len() counts its characters.

Text runs the world

Most of what you read on a screen is a string somewhere in a program.

  • Messageslen() checks a message is short enough before it is sent.
  • UsernamesSlices take the first letters of a name to suggest a username.
  • Searchin checks whether the words you typed appear in a title.
  • SubtitlesOne string type handles every language and alphabet in the world.

Cutting out a piece

A slice copies part of the text. Tap each part to see its job.

Part 1 of 5

Tap any part of the code below, or press Next.1 of 5 explored

text:Six characters at indexes 0 to 5: P is 0, Y is 1, T is 2 and so on.

Prints YTH

Take text apart

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Index it

Every character has a position, counting from 0.

Your turn: Print the middle letter using len(word) // 2 as the index.

Python
word = "rainbow"
print(word[0])
print(word[-1])
print(len(word), "letters")
Output
Press Run to see what it prints.

Watch a word turn into a secret code

Press Step to run one line at a time. Slices and joins turn planet into a playground secret language.

Ready. Press Step to run the first line.

  1. word = "planet"
  2. first = word[0]
  3. rest = word[1:]
  4. secret = rest + first + "ay"
  5. print(secret)
  6. print(len(word), len(secret))

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.What does this print?

print("abc"[-1])

0 of 6 answered

Common string misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Text as a sequence of characters

A string is an ordered sequence of characters: letters, digits, spaces, punctuation, even emoji and letters from any alphabet. You write one in single or double quotes; both make exactly the same kind of value.

Try it 1: edit me, then Run
greeting = "Hello"
reply = 'It\'s fine'
path = "C:\\photos"
print(greeting, reply, path)
Output
Press Run to see what it prints.

Inside quotes, a backslash starts an escape sequence: \n new line, \t tab, \' and \" quote characters, \\ a single backslash. The simplest way to avoid escaping quotes is to pick the other kind for the outside: "It's fine".

For text that spans several lines, use triple quotes, either """ or '''. Line breaks inside them become part of the string.

Try it 2: edit me, then Run
poem = """Roses are red,
violets are blue."""
print(poem)
Output
Press Run to see what it prints.

Length, indexes and slices

len() counts the characters, including spaces. Indexes start at 0 and negative indexes count from the end, exactly as with lists.

Try it 3: edit me, then Run
word = "Python"
print(len(word))       # 6
print(word[0])         # P
print(word[-1])        # n
print(word[1:4])       # yth
print(word[:2])        # Py
print(word[::-1])      # nohtyP
Output
Press Run to see what it prints.

A slice word[start:stop] goes up to but not including stop. Leaving out the start means "from the beginning" and leaving out the stop means "to the end". A step of -1 walks backwards, which reverses the string. An index past the end raises IndexError, but a slice past the end just returns what exists, so word[4:100] is on.

There is no separate character type in Python. word[0] is itself a string of length 1. Slicing is the tool for taking text apart: the first word of a fixed format, the year from "2024-06-15" with date[:4], or the last digits of a code with code[-4:].

Strings are immutable

Like tuples, strings cannot be changed after they are created. Assigning to an index is a TypeError.

Try it 4: edit me, then Run
name = "Jill"
name[0] = "B"      # TypeError: 'str' object does not support item assignment
name = "B" + name[1:]
print(name)        # Bill
Output
Press Run to see what it prints.

To change text, build a new string from pieces and, if you like, give the old name to the new value. Every string operation, including all the string methods in the next lesson, returns a new string and leaves the original as it was. That is why name.upper() on its own line does nothing useful: the uppercase copy is made and immediately thrown away.

Joining, repeating and comparing

+ joins two strings, * repeats one, and in checks whether one string appears inside another. These operations make new strings or bools and never change their inputs.

Try it 5: edit me, then Run
first = "Ada"
last = "Lovelace"
full = first + " " + last
print(full)
print("-" * len(full))
print("love" in full.lower())
Output
Press Run to see what it prints.

== compares two strings exactly, character by character, so capital letters and spaces count. < and > use dictionary order based on each character's code, and every uppercase letter comes before every lowercase one, so "Zoe" < "adam" is True. To compare without caring about case, convert both sides first with .lower().

Each character has a number, its Unicode code point. ord("A") is 65 and chr(66) is "B". You rarely need these, but they explain the ordering rules and are handy for simple codes such as a Caesar cipher.

Any language, any symbol

Python strings are Unicode, which means one string type covers every writing system: "café", "日本" and "Привет" are all ordinary strings, and len("café") is 4. You can index, slice and loop over them exactly as with English text. This matters as soon as your program handles real names, which come from all over the world. Never assume a name has only the letters A to Z, or that it fits a fixed number of characters. Problems with text encoding only appear when text is saved to files or sent across a network, which a later course covers.

Looping over text

A for loop visits a string one character at a time. Combined with an accumulator, that lets you count, filter or transform text.

Try it 6: edit me, then Run
message = "meet at noon"
vowels = 0
spaced = ""
for ch in message:
    if ch in "aeiou":
        vowels += 1
    spaced += ch + " "
print(vowels)
print(spaced)
Output
Press Run to see what it prints.

Building a long string with += in a loop is fine for short text. For large amounts of text, Python programmers collect pieces in a list and join them once, which the next lesson shows with str.join().

Converting to and from text

str() turns any value into its text form, and f-strings do the same inside a template. Going the other way, int() and float() read numbers written as text. Remember the rule from the input lesson: anything typed by a user, read from a file or received from the web starts life as a string.

Readable text in code

Keep long strings readable. Two string literals written next to each other inside brackets are joined automatically, so you can split a long message over several lines without +. Triple-quoted strings keep their indentation, so for messages inside a block it is often cleaner to build them from shorter pieces.

Syntax

The general shape of the statements in this lesson.

syntax.py
s = "text"   s = 'text'   s = """several
lines"""
len(s)   s[0]   s[-1]   s[1:4]   s[::-1]
s + "more"   "-" * 10   "ex" in s
s == t   s < t          # exact, dictionary order
"B" + s[1:]             # build a new string
ord("A")   chr(65)
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Initials and a username

Beginner

From a first and last name, print the initials and build a username from the first three letters of each name in lowercase.

Python
first = "Grace"
last = "Hopper"
initials = first[0] + "." + last[0] + "."
username = (first[:3] + last[:3]).lower()
print(initials)
print(username)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Indexing with [0] takes the first character and slicing with [:3] takes the first three. + joins the pieces into new strings, and .lower() returns a lowercase copy. Neither first nor last is changed.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Trying to change one character

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
word = "cat"
word[0] = "b"
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

TypeError: 'str' object does not support item assignment

Write this instead

word = "cat"
word = "b" + word[1:]

Why it happens

Strings are immutable. You cannot edit one in place.

In the real world

Where this shows up in software people use every day.

  1. Masking a card number on a receipt

    Retail

    Card receipts never show the whole card number. The till keeps the last four digits and replaces the rest with stars, so customers can recognise their card without exposing it.

    Why Python fits

    Repeating a star for every hidden digit and slicing the last four builds the masked text without touching the original. Slicing in steps of four then groups it the way people expect to read a card number.

    Python
    card = "4929123456781234"
    masked = "*" * (len(card) - 4) + card[-4:]
    grouped = ""
    for i in range(0, len(masked), 4):
        grouped += masked[i:i + 4] + " "
    print(grouped)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Should I use single or double quotes?

Either. Many Python projects use double quotes; pick one style and switch only when the text contains that quote.

How do I get the last three characters?

s[-3:] slices from three before the end to the end.

Why does len("hi there") give 8?

Spaces are characters too. h, i, space, t, h, e, r and e make eight.

Is an empty string the same as a space?

No. "" has length 0 and is falsy; " " has length 1 and is truthy. Cleaning user input often turns a string of spaces into an empty one with .strip().

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 7 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.