Basic

Strings and Text Operations

Slice, format, and manipulate text with Python's string methods.

What you will see

racecar olleh

About 2 min of reading

Quick check

Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.

Try It

Strings are immutable text you can slice, reshape, and query. I dig into a single word with indices and slices, run the common methods over it, then check what is and is not still there once the operations finish.

1

I open a word from both ends and cut pieces out of it. Indices start at 0 and count backward with negatives; slices stop one item early, so the ranges I read are never quite as long as they look.

text = "python" print(text[0]) print(text[-1]) print(text[1:4]) print(text[:3]) print(text[::2])

Before you run it, say out loud what it will print. Then open the answer.

What it prints
p n yth pyt pto
Slices are forgiving and never raise on an out-of-range index, but text[99] with a single index would raise IndexError.
2

The string methods hand me brand-new strings instead of changing the original. I strip the padding, shout it, swap a letter, split on a space, and join two letters, printing each result.

s = " Hello World " print(repr(s.strip())) print(s.upper()) print(s.replace('l', 'L')) print('a b c'.split(' ')) print('-'.join(['x', 'y']))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
'Hello World' HELLO WORLD HeLLo WorLd ['a', 'b', 'c'] x-y
Every method returns a new string; the original s is untouched, so reassign the result if you want to keep it.
3

Before I scan a sentence I want to know what tools exist. I check membership, count a letter, find where one lands, and ask whether it begins a certain way, printing the booleans and numbers back.

phrase = "the quick brown fox" print('quick' in phrase) print(phrase.count('o')) print(phrase.find('brown')) print(phrase.startswith('the'))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
True 2 10 True
find() returns the index or -1 when absent, while 'in' returns a plain boolean. Use 'in' for a yes/no check and find() for a spot.
4

Immutability is real, not just a claim. I add a word to an old one, keeping both, and confirm the original is still exactly what it was while the new text stands on its own.

s = "cat" t = s + "dog" print(s) print(t)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
cat catdog
s is still 'cat'. Each concatenation builds a fresh string, which is why joining a long text piece by piece is slow.
5

A slice with a negative step walks backward, which is the shortest way to flip a word. I reverse a palindrome to prove it works the same, then reverse a word that is not one.

word = "racecar" print(word[::-1]) msg = "hello" print(msg[::-1])

Before you run it, say out loud what it will print. Then open the answer.

What it prints
racecar olleh
'[::]' means every step; a step of -1 means every step backward. It never changes the original string, only a new one.

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

A string is stored immutably; methods read it and return fresh strings.
1 Text literal created -> immutable object
↓
2 Method called -> reads original, builds new string
↓
3 Slice computed via indices -> new substring object
↓
4 Result assigned to a name -> replaces old binding
Line by line

Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.

text = "python" sets nothing on screen
print(text[0]) p
print(text[-1]) n
print(text[1:4]) yth
print(text[:3]) pyt
print(text[::2]) pto
Why this works
Why strings are immutable

Once created, a string's bytes cannot change. This lets Python cache the length and hash, making strings fast as dict keys and safe to share. Every operation you think of as 'editing' actually allocates a new string:

s = "cat"
s = s + "dog"   # new object, old 'cat' may be garbage collected

For building many pieces, accumulate in a list and call ''.join() once, repeated + on large strings is O(n²).

Slicing semantics

The slice s[start:stop:step] always omits stop. If start is omitted it defaults to the beginning; if stop is omitted it defaults to the end. A negative step reverses:

word = "racecar"
print(word[::-1])   # 'racecar' reversed

Out-of-range indices never raise, slicing is forgiving, unlike single-index access which raises IndexError.

Examples

Indexing and slicing

Accessing parts of a string

text = "python"
print(text[0])     # p
print(text[-1])    # n (from the end)
print(text[1:4])   # yth
print(text[:3])    # py
print(text[::2])   # ptn

Slicing uses [start:stop:step]. The stop index is exclusive; negative indices count from the end.

Common string methods

Handy built-in methods

s = "  Hello World  "
print(s.strip())        # 'Hello World'
print(s.upper())        # 'HELLO WORLD'
print(s.replace('l','L'))
print('a b c'.split(' '))  # ['a','b','c']
print('-'.join(['x','y']))  # 'x-y'

Strings are immutable: every method returns a new string and never changes the original.

Counting and checking

Membership and queries

phrase = "the quick brown fox"
print('quick' in phrase)   # True
print(phrase.count('o'))   # 2
print(phrase.find('brown'))# 10
print(phrase.startswith('the'))  # True

find() returns -1 when absent, while in returns a boolean, use in for checks and find() when you need the position.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Variables and Types
Previous Lesson
Variables and Types
Next Lesson
Control Flow: Conditionals
Control Flow: Conditionals →