VMware ESXi and vSphere Cluster Management

Searching and Inspecting Strings in Python

Learn to use Python string methods count(), endswith(), find(), and replace() to search, inspect, validate, and transform text.

A string is an ordered sequence of text characters enclosed in quotes, such as "Hello" or 'notes.txt'. Programs often need to inspect strings to find words, count characters, check prefixes or suffixes, locate markers, and replace unwanted text.

Python provides built-in string methods for these tasks. A string method is an operation called with dot notation on a string value, such as message.count("red"). The methods in this lesson are built into Python's str type, so no package installation or configuration is required.

Core Python String Search Methods

MethodPurposeReturn typeResult when no match existsExample
count()Counts non-overlapping occurrencesInteger0text.count("a")
endswith()Tests whether text finishes with a suffixBooleanFalsetext.endswith(".")
find()Locates the first matching substringInteger index-1text.find("cat")
replace()Returns text with matching content substitutedStringReturns the original text if nothing matchestext.replace("old", "new")

Counting Occurrences with count()

Use string.count(substring) to count how many times a substring occurs. It returns an integer. A substring is a smaller sequence of characters searched for inside a larger string.

message = "red blue red"
occurrences = message.count("red")
print(occurrences)

Output:

2

You can count a single character as well:

text = "banana"
print(text.count("a"))
3

A result of 0 means that the searched value was not found. Matching is case-sensitive, so "Red" and "red" are different values.

Non-overlapping matches

count() counts non-overlapping occurrences. For example, the two matches in "aaaa" for "aa" use positions 0–1 and 2–3:

print("aaaa".count("aa"))
2

It does not count overlapping matches at positions 0–1, 1–2, and 2–3.

Testing Endings with endswith()

Use string.endswith(suffix) to test whether a string finishes with particular text. It returns a Boolean value: True or False.

filename = "notes.txt"
print(filename.endswith(".txt"))
True

This method is useful for checking punctuation, filename extensions, or required endings:

sentence = "The task is complete."
filename = "report.csv"

print(sentence.endswith("."))
print(filename.endswith(".txt"))
True
False

An ending check is not the same as searching anywhere in a string. For example, "notes.txt".endswith("txt") is true, but "txt notes".endswith("txt") is false because "txt" is not at the end.

Finding a Substring with find()

Use string.find(substring) to locate the first occurrence of a substring. It returns the match's zero-based index, meaning the first character has index 0, not 1.

message = "Hello world!"
position = message.find("llo")
print(position)
2

The characters in this example begin at these positions:

H e l l o   w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11

The substring "llo" begins at index 2. If no match exists, find() returns -1:

message = "Hello world!"
position = message.find("Python")
print(position)
-1

A common test is to compare the result with -1:

if message.find("world") != -1:
    print("The word was found")

Replacing Text with replace()

Use string.replace(old, new) to create a string in which matching text is substituted. The method returns the modified string; it does not change the existing string in place.

greeting = "Hello world!"
changed_greeting = greeting.replace("Hello", "Bye")
print(changed_greeting)
print(greeting)
Bye world!
Hello world!

Python strings are immutable: their existing characters cannot be changed directly. Assign the returned value to a new variable, or assign it back to the same variable:

word = "teh"
word = word.replace("teh", "the")
print(word)
the

By default, every matching occurrence is replaced:

text = "go go go"
print(text.replace("go", "stop"))
stop stop stop

An optional third argument limits the number of replacements:

text = "go go go"
print(text.replace("go", "stop", 1))
stop go go

Combining String Methods

Text-processing tasks often use several methods. For example, a program can count a marker, check the file type, locate the marker's first position, and clean a label.

filename = "report.txt"
message = "TODO: check data. TODO: send report."

print("TODO count:", message.count("TODO"))
print("Text file:", filename.endswith(".txt"))
print("First TODO position:", message.find("TODO"))
print(message.replace("TODO:", "Task:"))

Each method returns a different kind of value:

MethodTypical return valueHow to interpret itCommon conditional usage
count()Integer, such as 3Number of non-overlapping matchesif text.count("!") > 0:
endswith()True or FalseWhether the suffix is at the endif filename.endswith(".txt"):
find()Index or -1Where the first match beginsif text.find("TODO") != -1:
replace()New stringText after substitutionsclean = text.replace(" ", "_")

Case Sensitivity and Exact Matching

String searching is usually case-sensitive. This means uppercase and lowercase characters are treated as different characters.

message = "Welcome Python learner"
print(message.find("Python"))
print(message.find("python"))
8
-1

For a case-insensitive search, normalize both the text and the search value with lower():

message = "Welcome PYTHON learner"
found = message.lower().find("python") != -1
print(found)
True

Spaces and punctuation are also part of the searched text. A search for "Hello" does not match "Hello " with a trailing space, and a search for "world" does not include the exclamation mark in "world!".

Troubleshooting Common Results

find() returns -1

  • Check capitalization.
  • Check spaces, punctuation, and newline characters.
  • Make sure the exact searched text is present.
  • Use lower() on both values when case-insensitive matching is intended.

The index seems one position too high or low

Remember that indexes are zero-based. The first character is at index 0, the second at index 1, and so on.

replace() appears not to work

Print the method result or assign it. Calling text.replace("old", "new") without using its returned value leaves text unchanged.

count() gives an unexpected number

Check capitalization and remember that count() counts non-overlapping matches, not every possible overlapping position.

endswith() returns False unexpectedly

Inspect the final characters for extra spaces, a trailing newline, different punctuation, or a different suffix. Use strip() only when removing surrounding whitespace is appropriate for the task.

Practice Checklist

  • Use count() to summarize repeated words or characters.
  • Use endswith() to validate a file extension or required punctuation.
  • Use find() to determine where a marker begins and handle -1.
  • Use replace() to clean or transform text, assigning its returned string.
  • Check capitalization, spaces, and punctuation when an exact search fails.

These methods are a foundation for more string operations, including startswith() for prefix checks, in and not in membership tests, indexing and slicing, split(), strip(), and regular expressions.

Continue with Python string searching examples when you need a quick reference for these operations.