Python string methods
There are several string methods, which will be discussed one by one. To represent strings, we use the str1
variable.
Sometimes, we want to count the characters or substrings in the given string. The string method count
helps to achieve this:
count()
The syntax for the method is as follows:
str1.count(substr [, start [, end]])
The count method returns the number of occurrences of the substring substr
in string str1.
By using the parameter start
and end
you can obtain a slice of str1
.
Consider the following example:
>>> str1 = 'The Avengers' >>> str1.count("e") 3 >>> str1.count("e",5,12) 2 >>>Â
In many situations, we need to find the index of the substring in the given string. The find()
method can do the task.
The syntax for the find()
method is given as follows:
str.find(str, beg=0 end=len(string))
The find()
method is used to find out whether a string occurs in a given string or its substrings.
>>> str1 = "peace begins with a smile...