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"
>>> str1.find("with")
13
>>>

So 13 is the index value of substring "with" as shown here:

Showing index value of substring          

Let's discuss another example of the find method:

>>> str1 = "what we think, we become"
>>> str1.find("we")
5
>>>

In the preceding example, the  "we" substring occurs two times, but the find method will only give the index of the first occurrence.  If you want to find the occurrence from right, you can use the rfind method. Let's learn by example:

> str1 = "what we think, we become"
>> str1.rfind("we")
15
>>>

Sometimes, the user wants to find the index of a substring but is not sure about the cases. The substring may occur in lower, upper, or title cases. Python gives you some methods to deal with cases.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.247.68