PYTHON / VARIABLES AND DATA TYPES
Strings as a data type
Write Python string literals correctly, reason about escapes and raw strings, and treat a string as an indexable sequence of code points.
What you will learn
- Choose between ', ", and triple quotes based on what the text itself contains
- Predict what a backslash escape does before it silently changes your string
- Index, slice, and iterate a string, knowing each element is a 1-character str
- Use r"..." for text where backslashes must survive literally
Understanding Strings as a data type
A Python string is a single immutable sequence of Unicode code points, not an array of bytes and not a list of characters. That is why len("café") is 4 rather than 5: the accented letter is one code point, even though encoding it as UTF-8 would take two bytes. Because a string is a sequence, it supports the same operations as other sequences: s[0] for the first element, s[-1] for the last, s[1:3] for a slice, and `in` for a containment test.
There is no separate character type in Python. Indexing a string gives you another string of length 1, so word[0] is "b" and type(word[0]) is str. This is unusual compared with C or Java and it has a practical consequence: any function that accepts a string accepts a single letter too, and you never need conversions when moving between a letter and a one-letter string.
The quotes around a literal are source-code syntax, not part of the value. "hi" and 'hi' produce the identical object, so you pick whichever quote lets you avoid escaping: 'He said "no"' needs no backslashes at all. Inside a normal literal, a backslash starts an escape sequence, so \n becomes one newline character and \t becomes one tab. That rule is applied when the literal is compiled, which is why a mistyped Windows path can shrink or break before your program ever runs.
s = "café"
print(len(s))
print(s[0], s[-1])
print(s[1:3])
print(s + "!" * 3)
print("a" "b" "c")
print(ord("é"), chr(233))A string is an immutable sequence of Unicode code points, and literal syntax such as quotes and backslash escapes is only a way of spelling that sequence.
Worked examples
Escapes versus raw strings
Shows how a backslash in a normal literal is consumed as an escape, and how r"..." keeps it.
path = "C:\new_folder"
print(path)
print(len(path))
print(repr(path))
raw = r"C:\new_folder"
print(raw)
print(len(raw))Example explained
Line 1In the first literal, \n is one newline character, so printing it splits the text across two lines.
Line 2len(path) is 12 because the backslash and the n collapsed into a single code point.
Line 3repr(path) shows the escape form, which is the fastest way to see hidden control characters.
Line 4The r prefix disables escape processing, so the backslash stays and the length is 13.
A string is a sequence
Demonstrates indexing, membership, iteration, and the fact that indexing yields a str.
word = "banana"
print(type(word[0]))
print(word.count("na"), "an" in word)
letters = [c for c in word]
print(letters)
print("-".join(letters))Example explained
Line 1word[0] is a one-character string, so its type is str and not some char type.
Line 2count("na") finds two non-overlapping occurrences; membership with `in` works on substrings, not just single letters.
Line 3Iterating a string yields its code points one at a time, which is why the list comprehension gives six items.
Line 4join rebuilds a single string from those pieces using the separator as the caller.
Multi-line text and adjacent literals
Compares triple-quoted literals with the implicit concatenation of literals written side by side.
menu = """Soup
Bread
Water"""
print(menu)
print(len(menu.splitlines()))
sql = (
"SELECT name "
"FROM users "
"WHERE active = 1"
)
print(sql)Example explained
Line 1Triple quotes keep the real newlines you typed, so menu contains two newline characters.
Line 2splitlines() reports 3 lines, confirming the newlines are part of the value.
Line 3Two string literals separated only by whitespace are joined at compile time, with no + operator involved.
Line 4The trailing spaces inside each fragment matter, because nothing is inserted between them.
Important notes
len() counts code points, not bytes and not what the eye sees as one character; an accent typed as a separate combining mark makes a visually single letter count as 2.
Adjacent string literals are concatenated automatically, so a missing comma in a list of strings quietly merges two entries into one instead of failing.
Common mistakes
Typing a Windows path as "C:\report\new.csv": \r and \n become control characters, so the path silently points nowhere, and a path containing \U raises a SyntaxError about a unicode escape.
Writing "He said "no"": the second quote ends the literal, and the interpreter reports a SyntaxError on that line instead of building the string.
Concatenating a number with + as in "age " + 30: this raises TypeError because + between str and int is undefined; the number must become a string first.
Try it yourself
Change, predict, then run
Build the two-line text "Line one" then "Line two" twice: once with a triple-quoted literal and once with a single-line literal using \n. Print whether the two are equal and print len() of each.
Open the Python workspaceCheck your understanding
You store a Windows path as "C:\report\new.csv" and len() returns fewer characters than you typed. What happened?
- Python read \r and \n as escape sequences, so each pair of typed characters became one character
- Python removes backslashes from every string literal it compiles
- len() measures bytes, and backslashes occupy zero bytes
- The literal was truncated at the first backslash
Show answer
In a normal literal a backslash begins an escape sequence, so \r and \n each collapse into one control character, shortening the string. Option 2 is tempting because backslashes seem to vanish, but they are not stripped: a backslash followed by a character with no escape meaning, such as \q, is kept as two characters. The path is also not truncated; the rest of the text is still there, just with a carriage return and a newline embedded in it.