Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
String Basics & CreationString Indexing & SlicingCommon String MethodsString Formatting EssentialsFinding & Replacing TextString Testing & ValidationRegular Expression BasicsText Splitting & JoiningPractical String Projects
Python/String Manipulation/Finding Replacing Text

🔍 Finding & Replacing Text — Locate and Modify Content

Learn to search for substrings, find their positions, and replace them efficiently.


🎯 The find() Method

The `find()` method returns the index of the first occurrence. Returns `-1` if not found:

text = "Python is awesome. Python is fun."

position = text.find("Python")
print(position)  # 0 (first position)

position = text.find("is")
print(position)  # 7 (first "is")

position = text.find("xyz")
print(position)  # -1 (not found)

# Start search from specific position
position = text.find("Python", 10)  # Search from index 10
print(position)  # 20 (second Python)

💡 The index() Method

`index()` works like `find()` but raises an error if substring not found:

text = "Hello World"

print(text.index("o"))   # 4
print(text.index("xyz"))  # ValueError: substring not found

🎨 The count() Method

Count how many times a substring appears:

text = "apple apple apple"
count = text.count("apple")
print(count)  # 3

sentence = "The quick brown fox jumps over the lazy dog."
print(sentence.count("the"))  # 1 (case-sensitive)
print(sentence.count("the", 0, 20))  # Count within range

🔑 The replace() Method

Replace text with new content:

original = "I like cats. Cats are cute."

# Replace all occurrences
result = original.replace("cats", "dogs")
print(result)  # I like dogs. Cats are cute. (note: "Cats" not replaced)

# Case-sensitive replacement
result = original.replace("Cats", "Dogs")
print(result)  # I like cats. Dogs are cute.

# Replace first N occurrences
text = "one one one one"
result = text.replace("one", "two", 2)  # Replace first 2
print(result)  # two two one one

📊 Search & Replace Reference

MethodPurposeReturnsExample
`find()`Find first positionIndex or -1`"hello".find("l")` → `2`
`rfind()`Find last positionIndex or -1`"hello".rfind("l")` → `3`
`index()`Find positionIndex or error`"hello".index("l")` → `2`
`count()`Count occurrencesInteger`"aaa".count("a")` → `3`
`replace()`Replace textNew string`"hi".replace("h","H")` → `'Hi'`

💡 Real-World Example: Email Validation & Extraction

email = "john.doe@example.com"

# Check if it's an email
if "@" in email and "." in email:
    print("Valid format")

# Extract domain
at_pos = email.find("@")
domain = email[at_pos + 1:]
print(domain)  # example.com

# Replace domain
new_email = email.replace("@example.com", "@newcompany.com")
print(new_email)  # john.doe@newcompany.com

🎯 Conditional Replacement

text = "I have 5 apples and 3 apples"

# Replace only if found
if "apples" in text:
    text = text.replace("apples", "oranges")
    print(text)  # I have 5 oranges and 3 oranges

# Count before replacing
original = "The cat and the dog"
count_before = original.count("the")
result = original.replace("the", "a", 1)  # Replace first only
print(f"Found {count_before} occurrences")

🔑 Key Takeaways

ConceptRemember
find() returns indexFirst match position, or -1 if not found
Case mattersSearches are case-sensitive by default
replace() creates newOriginal string unchanged; reassign if needed
count() is usefulCheck existence before replacing
Limit replacementsUse `replace(old, new, count)` to limit changes

🔗 What's Next?

Learn to validate strings and test characters.


Ready to practice? Challenges | Quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn