How to Count the Number of Occurrences of a Substring in Python (Case-Insensitive)?

Estimated read time 2 min read

In Python, you can count the number of occurrences of a substring in a string in a case-insensitive manner by converting both the substring and the string to lowercase (or uppercase) using the lower() method before performing the count. Here’s an example:

# Define the input string
input_string = "The quick brown fox jumps over the lazy dog. The Quick BROWN fox is fast."

# Define the substring to count
substring_to_count = "quick"

# Convert both the input string and substring to lowercase (or uppercase)
input_string_lower = input_string.lower()
substring_to_count_lower = substring_to_count.lower()

# Call the count() method on the lowercase input string
substring_count = input_string_lower.count(substring_to_count_lower)

# Print the result
print("The substring '{}' appears {} times in the string (case-insensitive).".format(substring_to_count, substring_count))


The substring 'quick' appears 2 times in the string (case-insensitive).

In this example, the lower() method is called on both the input_string and substring_to_count to convert them to lowercase, and then the count() method is called on the lowercase input_string to count the occurrences of the lowercase substring_to_count. Finally, the result is printed using a formatted string to display the substring and its count in a case-insensitive manner.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply