← Python from Scratch Lesson 13 of 78 · 10 XP

Strings

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A string is a sequence of characters. You can access each character by its index — a number that starts at zero:

word = "Python"
word[0]     # 'P'
word[1]     # 'y'
word[-1]    # 'n'  — negative indices count from the end
len(word)   # 6    — the length of the string

Slices cut out a piece of a string: string[start:end], and the end is not included.

word[0:3]   # 'Pyt'
word[2:]    # 'thon' — to the end
word[:2]    # 'Py'   — from the start
word[::-1]  # 'nohtyP' — a step of -1 reverses the string

Strings are immutable: word[0] = "J" raises an error. To "change" a string, you create a new one: "J" + word[1:].

Task. Read a word and print, on three lines: its first character, its last character and its length.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.