Python Strings Introduction
In this page:
variable = "text"
variable = 'text'
variable = """multi-line
text"""
Creating Strings
A string is an ordered sequence of characters, and Python lets you create one with single quotes, double quotes, or triple quotes — all three produce the exact same str type, so the choice comes down to convenience, like avoiding escaping an apostrophe.
Example: Creating Strings
s1 = 'single'
s2 = "double"
s3 = """triple"""
print(type(s1), type(s2), type(s3)) # all three are the same str type
Accessing Characters
Square-bracket indexing, like text[0], retrieves a single character at that zero-based position; Python also supports negative indices, so text[-1] retrieves the last character without needing to know the string's length first.
Example: Accessing Characters
text = "Python"
print(text[0]) # first character, index 0
print(text[-1]) # last character, negative indexing counts from the end
String Length
len(text) returns the total character count of a string, including spaces and punctuation — a value you'll reach for constantly when validating input length or iterating with an index-based loop.
Example: String Length
text = "Hello, World!"
print(len(text))
Multiline Strings
Triple-quoted strings ("""...""") can span multiple lines exactly as typed, preserving line breaks — the standard way to embed a block of formatted text, a docstring, or a multi-line message without manual \n characters.
Example: Multiline Strings
message = """Line one
Line two
Line three""" # triple quotes preserve the line breaks as typed
print(message)
Immutability of Strings
Once created, a Python string can never be modified in place — operations like .upper() or .replace() don't change the original string, they return a brand-new one, leaving the original untouched in memory.
Example: Immutability of Strings
text = "hello"
upper_text = text.upper() # returns a new string, doesn't modify text
print(text) # still lowercase
print(upper_text)
- Trying to change a character in place with
s[0] = "J", which raisesTypeErrorbecause strings are immutable; build a new string instead. - Using an index equal to the length, as in
s[len(s)], which raisesIndexErrorsince valid indexes end atlen(s) - 1. - Forgetting that
len()counts characters and spaces, solen("hi there")is 8, not 2.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: