How to Count the Number of Occurrences of ‘hi’ in a String in Python?

Estimated read time 2 min read

In Python, you can count the number of occurrences of a specific substring, such as ‘hi’, in a string by using the built-in string method count(). Here’s an example:

# Define the input string
input_string = "hi there! hi, how are you? hihi"

# Define the substring to count
substring_to_count = "hi"

# Call the count() method on the input string
substring_count = input_string.count(substring_to_count)

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

Output:

The substring 'hi' appears 3 times in the string.

In this example, the count() method is called on the input_string and takes the substring_to_count as an argument. It returns the number of occurrences of the substring in the input string, which is stored in the substring_count variable. Finally, the result is printed using a formatted string to display the substring and its count. Note that the count() method performs a case-sensitive search, so it will not match substrings with different capitalization, such as ‘Hi’ or ‘HI’. If you want to perform a case-insensitive search, you can convert both the input string and the substring to lowercase (or uppercase) using the lower() method before calling the count() method, as shown in the previous examples.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply