There are lots of string methods that we can use. In one of my previous articles I was talking about string formatting methods. If you haven’t read it, feel free to do it. Today we’ll be talking about string statistical methods.
The first method we’re going to talk about is the len method. The len method returns the length of a string:
>>> len("No one knows how many characters there are in this string.")
58
There are other statistical methods. Here’s the count method.
The method count counts how many times a substring occurs in a string. The first parameter is the substring. The second and third parameters, which are optional, are the start and past indices between which the substring is searched.
>>> text = "Let's see if there are any repetitions in this text."
How many times does ‘re’ occur in the string?
>>> text.count("re")
3
Or how many times does the letter “e” occur from index 10 to the end?
>>> text.count("e", 10)
6
Finally, how many times does the letter “e” occur between index 10 and 20?
>>> character = "e"
>>> text.count(character, 10, 21)
2
Here’s the video version of the article: