loop
Working with strings

Module 2 · Working with strings · Lesson 1 of 4

Inside a string

You've been writing strings since your very first print. Now look inside one. A string is an ordered sequence of characters, and that means you can reach into it exactly like a list: by index, and by slice.

word = "python"
0p-6
1y-5
2t-4
3h-3
4o-2
5n-1

Same rules as list indexing: word[0] is the first character, word[-1] the last, and word[0:3] is a slice (the stop is excluded). len() counts the characters.

Run it yourselfruns in your browser · Python
main.py

One crucial difference from a list, though: a string is immutable. You can read any part of it, but you can't change a character in place — trying to is a TypeError. Instead, you build a new string, which is exactly what the methods in the next lesson do.

Run it yourselfruns in your browser · Python
main.py
✎ Your turnauto-checked · Python

Given word = 'programming', use slicing to build first4 (the first four characters) and last3 (the last three).

solution.py