Searching and replacing text in Python strings is something you do constantly in real programs. You search to find whether a keyword appears in user input, to locate a specific section of a log file, to extract data between known markers, or to validate that a filename has the expected extension. You replace to clean up messy data, to substitute placeholder values in templates, to normalize inconsistent formatting, or to redact sensitive information before displaying output. Python provides a small set of methods that handle all of these tasks with clear, readable syntax and no external imports.
This article covers the core search methods find() and index(), the boundary-checking methods startswith() and endswith(), and the replacement method replace(). Each of these methods works directly on string objects and returns results that respect Python's string immutability: search methods report positions without modifying anything, and replace() returns a new string rather than altering the original. If you are comfortable with the foundational concepts from earlier in this section, including how common string operations like the in operator work and why string immutability matters for every method you call, you are ready to add search and replace to your toolkit.
Finding substrings with find() and index()
The find() method searches a string for a given substring and returns the index where that substring first appears, or -1 if it is not found anywhere in the string. This is the workhorse method for locating text, and you will use it whenever you need to know the exact position of a match rather than simply whether a match exists. The search moves from left to right through the string and stops at the first occurrence.
text = "The quick brown fox jumps over the lazy dog"
position = text.find("fox")
print(position) # 16
print(text.find("cat")) # -1You can narrow the search to a specific slice of the string by passing optional start and end indices. These work exactly like slice indices: the start is inclusive and the end is exclusive, and the search only examines characters in that range. This is useful when you need to find the second or third occurrence of a pattern by starting the next search just after the previous match.
The index() method behaves identically to find() except for what happens when the substring is not found: instead of returning -1, it raises a ValueError. Choose find() when a missing substring is a normal and expected possibility that your code handles gracefully, and choose index() when a missing substring indicates a genuine error that should stop execution. In most beginner code, find() is the safer default because it avoids unexpected crashes from unvalidated input.
Boundary checks with startswith() and endswith()
The startswith() method checks whether a string begins with a specified prefix and returns True or False. The endswith() method does the same for suffixes. These are simple methods that replace manual slice-and-compare patterns and make your intent clear at a glance.
Both methods accept optional start and end indices to check only a portion of the string, and both accept a tuple of strings to test against multiple possibilities in a single call. The tuple feature is particularly useful for checking file extensions or URL schemes where several valid options exist.
filename = "report.pdf"
print(filename.endswith(".pdf")) # True
print(filename.endswith((".pdf", ".txt"))) # True
url = "https://example.com"
print(url.startswith(("http://", "https://"))) # TrueThese boundary methods complement find() and the in operator. Use startswith() and endswith() when the match must appear at the edges of the string, and use find() or in when the match can appear anywhere. Mixing them up is a common beginner mistake: checking whether a string ends with a certain extension using in will incorrectly match if the extension text happens to appear earlier in the string.
Replacing text with replace()
The replace() method returns a new string in which every occurrence of a given substring has been replaced with another substring. The original string is never modified because strings are immutable; if you want to keep the result, you must assign it to a variable. The simplest form takes two arguments: the text to find and the text to substitute in its place.
By default, replace() replaces every occurrence it finds, scanning from left to right through the entire string. You can limit the number of replacements by passing a third integer argument. Only the leftmost occurrences up to that count are replaced, and any remaining occurrences are left untouched. This is useful when you want to replace only the first instance of a pattern, or when you are processing structured text where later occurrences have a different meaning.
To replace multiple different substrings in one pass, chain replace() calls together. Each call returns a new string, and the next call operates on that result. For more complex replacement logic involving patterns rather than literal text, Python's re module provides regular expression-based substitution, but for the vast majority of everyday text cleanup tasks, the built-in replace() method is exactly what you need and far simpler to use correctly.
Rune AI
Key Insights
- Use find() to get the index of a substring or -1 if not found; use index() if you want an exception instead.
- The replace() method swaps substrings and returns a new string; pass a third argument to limit the count.
- startswith() and endswith() check string boundaries and accept tuples for multiple patterns.
- The in operator is preferred over find() when you only need a yes-or-no containment check.
- All search and replace methods respect Python's string immutability and return new strings.
Frequently Asked Questions
How do I find a word inside a Python string?
How do I replace text in a Python string?
How do I check if a string starts or ends with specific text?
Conclusion
Python gives you a focused set of tools for searching and replacing text that handle the vast majority of everyday needs. find() and index() locate substrings, replace() swaps them out, and startswith() with endswith() check boundaries. Combine these with the in operator and slicing, and you can handle nearly any text-matching task without reaching for regular expressions.
More in this topic
Create and Assign Variables in Python
Learn every way to create and assign variables in Python, from basic single assignment to expressions, type hints, and practical patterns beginners use every day.
Python Variable Naming Rules
Learn Python's variable naming rules, including allowed characters, reserved keywords, PEP 8 conventions, and how to choose names that make your code readable.
Python Variables Explained
Understand what Python variables are, how they store and reference data, and why Python's variable model is different from other programming languages.