Python | Frequency of substring in given string

Python | Frequency of substring in given string

To find the frequency of a substring in a given string in Python, you can use the str.count() method. The method returns the number of non-overlapping occurrences of the substring in the given string.

Here's a simple function to demonstrate this:

def substring_frequency(main_string, substring): return main_string.count(substring) # Test s = "hello world, hello universe, hello everyone" sub = "hello" print(f"The substring '{sub}' appears {substring_frequency(s, sub)} times in the main string.") 

This will output:

The substring 'hello' appears 3 times in the main string. 

Note: This method counts only non-overlapping occurrences. For example, in the string "ababa", the substring "aba" appears only once, not twice.


More Tags

public-key six jdbc-odbc refactoring pywinauto structure battery nuget nslayoutconstraint tree-traversal

More Programming Guides

Other Guides

More Programming Examples