Python Find – String find() Method

I gonna explain some basic concepts of python  “Python Find nth occurrence of a substring in a string“. In the previous lecture, we have been learned to find the position of the specific word in a paragraph. So let’s start to learn.

Python Find – String find() method

To find the second word’s position. First, we find the 1st keyword position then calculate second by using find an operator.

python string find

Are you wanna know about Python vs PHP & Which programming language is better? then must-read.

Let we take an example

Python find the second (nth) occurrence in the string

How to Python find the position of the Second same substring or keyword in a given string?

Example:1

Note: In given String two “web” keywords are used. Now, we can calculate the position of the second “web” keyword in a given string.

First, we can calculate the first sub-string position then we can calculate the second same sub-string position.

para = "I am web Developer and SEO experts and web based application"
position1 = (para.find("web"))
#Above line is used to calculate the position of first "web".
position2 = (para.find("web"), position1+1)
#Above line is used to calculate the position of second "web" keyword.
print (position1)  # print first keyword position
print (position2)  # print second keyword position

Output:
5
39

python string find method

Description: when we find the position of the second same word in a paragraph then we used also the first position to increment (plus one).

An increment of plus one in the first position is used to calculate the position of the second same keyword.

Are you wanna know about Best web Development frameworks in 2020? then must-read.

How to check the position of the substring is correct or not?

Let we take the above example

Example:2

para = "I am web Developer and SEO experts and web based application"
position1 = (para.find("web"))
position2 = (para.find("web",position1+1))
print (position2)
print (para[position2: ])

Output: web based application

Description: The last line of the program is used to print the remaining line after the second web word to check whether it is the correct output or not.

Are you want to know more about string?, please read Python Documentation.

I hope this article is very helpful “How Python Find nth occurrence of a substring in a string”.

If you have any queries about this lecture, you will discuss it in the comments section.

Some Useful Article Links

Django vs Laravel – Which is the best Web Development Framework in 2020?

Add a Comment

Your email address will not be published. Required fields are marked *