Python Strings
Python strings are sequences of characters used to store text. You create a string by placing text inside single quotes or double quotes. Triple quotes create a string that spans several lines.
Creating Strings
greeting = "Hello"
name = 'Bilal'
poem = """Roses are red,
Python is neat."""
print(greeting, name)
print(poem)
print(len(name))Hello Bilal Roses are red, Python is neat. 5
Indexing and Slicing Strings
Each character has a position (index) starting from 0. Negative indexes count from the end. A slice [start:end] returns the characters from start up to, but not including, end.
word = "Programming"
print(word[0])
print(word[-1])
print(word[0:7])
print(word[3:])
print(word[::-1])P g Program gramming gnimmargorP
Leaving out start or end means "from the beginning" or "to the end". A step of -1, as in [::-1], walks backwards and reverses the string.
Common Python String Methods
Strings come with many built-in methods. Because strings are immutable, each method returns a new string.
text = " Learn Python Today "
print(text.strip())
print("[" + text.lower() + "]")
print(text.upper().strip())
print(text.replace("Today", "Now").strip())
print(text.split())
print("-".join(["2026", "10", "31"]))Learn Python Today [ learn python today ] LEARN PYTHON TODAY Learn Python Now ['Learn', 'Python', 'Today'] 2026-10-31
Check if a String Contains Text
Use the in keyword to test whether one string appears inside another. startswith(), endswith() and find() give more control.
email = "naeem@example.com"
print("@" in email)
print(email.endswith(".com"))
print(email.find("@"))
print(email.count("e"))True True 5 4
Joining Strings and f-strings
The + operator joins (concatenates) strings and * repeats them. To mix text and variables, f-strings are the modern, readable choice: put f before the quotes and variables inside curly braces.
first = "Sara"
last = "Khan"
score = 92.456
print(first + " " + last)
print("=" * 10)
print(f"{first} scored {score:.1f} points")Sara Khan ========== Sara scored 92.5 points
Escape Characters
Some characters need a backslash in front of them inside a string:
- \n starts a new line
- \t inserts a tab
- \" or \' puts a quote inside a string using the same quote type
- \\ produces a single backslash
- Prefix a string with r (a raw string) to turn escapes off, useful for Windows paths and regular expressions
Frequently asked questions
How do I get the length of a string in Python?
Use the built-in len() function. For example len("hello") returns 5.
How do I reverse a string in Python?
Use slicing with a step of -1: text[::-1]. It returns a new reversed string.
Single or double quotes in Python: which is better?
They are identical. Pick one style and stay consistent; use the other kind when the text itself contains quotes, like "It's easy".
How do I check if a string contains a substring in Python?
Use the in operator, for example "py" in "python" returns True. Use find() if you also need the position.