Python 101Free
FOUNDATIONS

Strings

Text as a sequence of characters, and the methods you reach for daily.

SECTION 01

Indexing and slicing

A Python string is a sequence of characters with zero-based indexing. "hello"[0] is "h". Negative indices count from the end, so "hello"[-1] is "o". The bracket form picks one character.

Slicing picks a range. "hello"[1:4] is "ell". The slice is half-open, the start is included, the end is not. Either bound can be omitted and an optional third value sets the step. "hello"[::-1] reverses the string by stepping backwards.

Slicing always produces a new string. Strings are immutable, so there is no way to modify one in place. Any operation that looks like it changes a string is actually returning a new one and rebinding the name.

python
s = "hello"
s[0]      # 'h'
s[-1]     # 'o'
s[1:4]    # 'ell'
s[::-1]   # 'olleh'
2 more sections

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in