Reading — step 1 of 8
Learn
Strings are the most common data type you'll work with. User input, file names, web page content, database records, log messages — they're all strings. Python gives you a rich set of tools for working with text. This lesson covers the foundational operations: measuring, indexing, slicing, concatenating, repeating, and searching.
Strings are sequences of characters
A string is just an ordered sequence — like a list of single-character pieces, but immutable. Each position has an index:
P y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
- Indices count from 0 forward.
- Negative indices count from the end backward (
-1is the last). - Out-of-range indexing raises
IndexError.
len() — how long is it
Slicing — extract a substring
Note: out-of-range slice indices DON'T error — Python clamps them. "abc"[0:100] returns "abc". This is opposite to indexing behavior!
Concatenation and repetition
+ joins strings. * with an integer repeats. You CAN'T do "a" + 1 — you'd need "a" + str(1) or use an f-string.
Membership and counting with in
For counting: use the method "banana".count("a") → 3.
Strings are IMMUTABLE
You cannot change a character in place:
Instead, build a NEW string:
Every "modification" to a string really creates a new string object. This is why concatenating thousands of strings in a loop with += is slow — it creates and discards many intermediate strings. For heavy concatenation, build a list and "".join(parts).
Iterating over a string
A for loop on a string yields one character at a time.
Multi-line strings
Triple quotes (single OR double, but matched) span multiple lines:
The newlines inside become real \n characters in the string.
Escape sequences
Inside a string, certain backslash sequences mean special characters:
\n— newline\t— tab\\— a literal backslash\"— a literal double quote inside"..."\'— a literal apostrophe inside'...'
Common mistakes
- Trying to mutate a string:
s[0] = "X"raises TypeError. Build a new string instead. - Off-by-one in slices:
s[0:3]is THREE chars (0, 1, 2), not four. The stop is exclusive. - Forgetting that
*needs an integer, not a string:"a" * "3"is a TypeError. - Confusing
len()with the highest index:len("abc")is 3 but the highest valid index is 2.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…