Python Strings: A Complete Guide
Learn Python strings from scratch: creation, indexing, slicing, f-strings, built-in methods, and common gotchas with runnable examples.
Strings are one of the most-used data types in Python. Every time your program reads a file, displays a message, or parses input, it works with strings. This chapter covers how to create strings, index and slice them, use built-in methods, and avoid common pitfalls.
What Is a String in Python?
A string is an ordered, immutable sequence of Unicode characters. "Immutable" means you can never change a character in place — every operation that appears to modify a string actually creates a new one. Strings can contain letters, digits, punctuation, whitespace, or any Unicode character (emoji included).
greeting = "Hello, world!"
print(type(greeting)) # <class 'str'>
print(len(greeting)) # 13Creating Strings
Python accepts three quoting styles, which are all equivalent:
single = 'Python'
double = "Python"
triple = """Python""" # triple-double also works as '''Python'''Single and double quotes
Use whichever avoids escaping the quote character inside the string:
message1 = "It's a great day" # apostrophe is fine inside double quotes
message2 = 'She said "hello"' # double quote is fine inside single quotesTriple-quoted (multiline) strings
Triple quotes let a string span multiple lines without any escape sequences:
poem = """Roses are red,
Violets are blue,
Python is awesome,
And so are you."""
print(poem)Output:
Roses are red,
Violets are blue,
Python is awesome,
And so are you.Triple-quoted strings are also the conventional way to write docstrings — the documentation blocks that appear at the top of functions, classes, and modules.
Converting other types to strings
Use the built-in str() function to convert any object to its string representation:
num = 42
pi = 3.14
flag = True
print(str(num)) # '42'
print(str(pi)) # '3.14'
print(str(flag)) # 'True'Indexing Characters
Python uses zero-based indexing: the first character is at index 0. You can also use negative indexes — -1 refers to the last character, -2 to the second-to-last, and so on.
Accessing an index outside the valid range raises an IndexError.
Slicing Strings
A slice extracts a portion of a string using the syntax s[start:stop:step].
| Part | Meaning | Default |
|---|---|---|
start | Index of the first character to include | 0 |
stop | Index of the first character to exclude | len(s) |
step | How many characters to advance each time | 1 |
s = "Hello, World!"
print(s[0:5]) # Hello — characters at indexes 0–4
print(s[7:]) # World! — from index 7 to the end
print(s[:5]) # Hello — from the start to index 4
print(s[-6:]) # World! — last 6 characters
print(s[::2]) # Hlo ol! — every other character
print(s[::-1]) # !dlroW ,olleH — reversed stringFor a deeper look at slicing syntax, see the Slicing Strings chapter.
String Concatenation and Repetition
The + operator joins two strings; the * operator repeats a string a given number of times.
For large-scale concatenation inside a loop, use str.join() instead of + — it is significantly faster because it avoids creating intermediate string objects:
words = ["one", "two", "three"]
result = ", ".join(words)
print(result) # one, two, threeString Repetition
The in and not in Operators
Check whether a substring exists inside a string with in or not in:
text = "The quick brown fox"
print("quick" in text) # True
print("slow" in text) # False
print("slow" not in text) # TrueString Length
len() returns the number of characters in a string:
s = "Python"
print(len(s)) # 6
empty = ""
print(len(empty)) # 0Escape Characters
Some characters cannot be typed literally inside a string. Python uses a backslash \ to introduce escape sequences:
| Sequence | Character |
|---|---|
\n | Newline |
\t | Tab |
\\ | Literal backslash |
\' | Single quote |
\" | Double quote |
\r | Carriage return |
print("Line one\nLine two")
# Line one
# Line two
print("Name:\tAlice")
# Name: Alice
path = "C:\\Users\\Alice"
print(path) # C:\Users\AliceTo disable escape processing entirely, prefix the string with r to create a raw string — useful for regular expressions and Windows paths:
pattern = r"\d+\.\d+" # treated literally, no escaping needed
print(pattern) # \d+\.\d+See the Escape Characters chapter for the full list.
String Formatting
Python offers several ways to embed variable values inside strings.
f-strings (recommended — Python 3.6+)
An f-string is prefixed with f or F. Expressions inside {} are evaluated at runtime:
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# My name is Alice and I am 30 years old.
# Expressions work too
print(f"Next year I'll be {age + 1}.") # Next year I'll be 31.str.format() method
Percent (%) formatting (legacy)
Older Python code uses % formatting. You will still encounter it, but f-strings are the modern preference:
print("Hello, %s!" % "Dave") # Hello, Dave!
print("Pi ≈ %.2f" % 3.14159) # Pi ≈ 3.14For a full breakdown of formatting options, see the String Formatting and f-Strings chapters.
Common String Methods
Python's str type ships with dozens of built-in methods. The most frequently used ones are shown below.
Case conversion
s = "Hello, World!"
print(s.upper()) # HELLO, WORLD!
print(s.lower()) # hello, world!
print(s.capitalize()) # Hello, world!
print(s.title()) # Hello, World!
print(s.swapcase()) # hELLO, wORLD!Searching and counting
s = "hello, world"
print(s.find("o")) # 4 — index of first 'o', or -1 if not found
print(s.rfind("o")) # 8 — index of last 'o'
print(s.count("l")) # 3 — total occurrences of 'l'
print(s.startswith("he")) # True
print(s.endswith("ld")) # TrueReplacing substrings
s = "I like cats. Cats are great."
print(s.replace("cats", "dogs"))
# I like dogs. Cats are great. (only lowercase 'cats' replaced)
print(s.replace("cats", "dogs").replace("Cats", "Dogs"))
# I like dogs. Dogs are great.Stripping whitespace
padded = " hello "
print(padded.strip()) # 'hello' — both ends
print(padded.lstrip()) # 'hello ' — left end only
print(padded.rstrip()) # ' hello' — right end onlySplitting and joining
csv = "apple,banana,cherry"
items = csv.split(",")
print(items) # ['apple', 'banana', 'cherry']
print(" | ".join(items)) # apple | banana | cherryChecking string content
For the complete reference, see the String Methods chapter.
String Immutability — A Common Gotcha
Strings cannot be changed in place. Trying to assign to an index raises a TypeError:
s = "hello"
# s[0] = "H" # TypeError: 'str' object does not support item assignmentTo change part of a string, build a new one:
s = "hello"
s = "H" + s[1:] # slice off everything after index 0 and prepend "H"
print(s) # HelloThe variable name s now points to a different string object — the original "hello" is unchanged (and will be garbage-collected if nothing else references it).
Strings vs. bytes
A Python string (str) holds Unicode text. When you need raw binary data — for example, to write to a file in binary mode or send data over a network — use bytes instead:
b = b"hello" # bytes literal
s = b.decode("utf-8") # bytes → str
b2 = s.encode("utf-8") # str → bytes
print(type(b)) # <class 'bytes'>
print(type(s)) # <class 'str'>