A substring is part of a string. Python does not have a separate substr() function like some languages. To get a substring, use slicing: string[start:stop]. To check whether a substring exists, use the in operator.
Tested on: Python 3.13.3; kernel 6.14.0-37-generic.
Python substring quick reference
| Task | Use |
|---|---|
| Get substring by index | text[start:stop] |
| Get substring with step | text[start:stop:step] |
| Get first n characters | text[:n] |
| Get last n characters | text[-n:] |
| Remove first n characters | text[n:] |
| Remove last n characters | text[:-n] |
| Reverse a string | text[::-1] |
| Check if substring exists | substring in text |
| Find substring position | text.find(substring) |
| Raise error if not found | text.index(substring) |
| Count substring occurrences | text.count(substring) |
| Replace substring | text.replace(old, new) |
What is a substring in Python?
- A substring is a smaller part of a string.
- Python strings are sequences, so you access parts with indexes and slicing.
- Python has no direct
substr()method. - Slicing is the normal Python way to extract a substring.
Python substring syntax using slicing
Syntax:
string[start:stop:step]startis includedstopis excludedstepis optional (defaults to1)- Missing
start→ begin at index0 - Missing
stop→ go to the end
Get substring from start and end indexes
Use text[start:stop]. The stop index is not included:
text = "Learn Python Substring"
part = text[6:12]
print(part)The output is Python—indexes 6 through 11 only.
This is the closest Python equivalent to substring extraction in many other languages.
Get first n characters from a string
Use text[:n]:
code = "ABCD-1234-XY"
prefix = code[:5]
print(prefix)The output is ABCD-—the first five characters.
Get last n characters from a string
Use text[-n:]:
filename = "report_2024.pdf"
extension = filename[-4:]
print(extension)The output is .pdf.
Get substring from a specific index to the end
Use text[start:]:
text = "version:3.13.3"
value = text[8:]
print(value)Everything after index 8 prints as 3.13.3.
Get substring before a specific index
Use text[:stop]:
text = "0123456789ABCDEF"
before = text[:10]
print(before)Output is 0123456789—everything before index 10.
Get substring using negative indexes
Negative indexes count from the end:
-1is the last character-n:takes the lastncharacters
word = "Python"
print(word[-1])
print(word[-3:])Output is n and hon.
Get substring with step value
Use text[start:stop:step]:
text = "abcdefghij"
every_second = text[0:10:2]
reversed_text = text[::-1]
print(every_second)
print(reversed_text)You get acegi and jihgfedcba. Step 2 skips every other character; step -1 reverses the string. See reverse string in Python for more reversal patterns.
Check if a substring exists in a string
Use substring in text—it returns True or False:
email = "user@example.com"
filename = "notes.txt"
sentence = "Python makes substring checks easy"
print("@" in email)
print(".txt" in filename)
print("Java" in sentence)Results are True, True, and False. For more ways to test containment, see check if a string contains a substring.
Find substring position using find()
find() returns the first index where the substring starts, or -1 if it is not found:
text = "this is Bashir Alam"
print(text.find("Bashir"))
print(text.find("Khan"))
print(text.find("is"))Output is 8, -1, and 2. find() is case-sensitive—find("bashir") would return -1.
find() vs index()
| Method | If found | If not found | Best for |
|---|---|---|---|
find() |
Returns index | Returns -1 |
Safe position lookup |
index() |
Returns index | Raises ValueError |
When a missing substring is an error |
text = "hello world"
print(text.find("world"))
print(text.index("world"))
try:
print(text.index("planet"))
except ValueError as e:
print(e)You get 6, 6, then a ValueError for "planet".
Count substring occurrences
text.count(substring) counts non-overlapping matches and is case-sensitive:
text = "banana"
print(text.count("an"))
print(text.count("na"))
print("aaaa".count("aa"))Output is 2, 2, and 2. The last line shows non-overlapping behavior: "aaaa" has two "aa" matches, not three overlapping ones.
Replace a substring in Python
replace(old, new) returns a new string—strings are immutable:
text = "Hello World"
updated = text.replace("World", "Python")
print(updated)
print(text)Output is Hello Python; the original text is unchanged.
Extract substring after or before a character
Locate the marker with find(), then slice:
email = "user@example.com"
at = email.find("@")
if at != -1:
domain = email[at + 1:]
print(domain)
path = "folder/report.pdf"
dot = path.rfind(".")
if dot != -1:
name = path[:dot]
ext = path[dot:]
print(name)
print(ext)
line = "status: active"
colon = line.find(":")
if colon != -1:
value = line[colon + 1:].strip()
print(value)You get example.com, folder/report, .pdf, and active. Always check find() ≠ -1 before slicing. To break the line into fields first, see Python split string.
Extract substring between two characters
Find a start marker and end marker, then slice between them:
text = "result (Python) done"
start = text.find("(")
end = text.find(")")
if start != -1 and end != -1 and end > start:
inner = text[start + 1:end]
print(inner)
quote = 'name="Alice"'
q1 = quote.find('"')
q2 = quote.find('"', q1 + 1)
if q1 != -1 and q2 != -1:
print(quote[q1 + 1:q2])Output is Python and Alice. For complex patterns, consider regular expressions.
Case-insensitive substring check
Normalize case first with lower() or casefold(), then use in or find():
title = "Python Substring"
print("python" in title.lower())
print(title.casefold().find("substring") != -1)Both checks return True. Prefer casefold() for robust case-insensitive matching.
Python substring with regex
Use re when slicing or find() is not enough—for patterns, not fixed indexes:
import re
text = "Order ID: 48291, total $19.99"
digits = re.search(r"\d+", text)
print(digits.group() if digits else None)
email_like = re.findall(r"\b[\w.-]+@[\w.-]+\.\w+\b", "Contact admin@site.org today")
print(email_like)You get 48291 and ['admin@site.org']. Keep regex for pattern work; use slicing for fixed positions. See Python regex for broader pattern-matching examples.
Summary
A substring is part of a string. Use slicing (text[start:stop]) to extract it. Use in to test presence. Use find() or index() for position. Use count() for occurrences and replace() to substitute text. Use regex only when you need pattern-based extraction.
Useful references

