Important Notice:

Course Content
The Calendar Module
Library Function/Predefined Functions
0/4
Sys Module
Library Function/Predefined Functions
0/2
OS Module
Library Function/Predefined Functions
0/2
Functions in Python (Chapter-10) M3-R5
About Lesson

Index():-

            The index() method finds the first occurrence of the specified value. The index() method raises an exception if the value is not found.

              The index() method is almost the same as the find() method, the only difference is that the find() method returns -1 if the value is not found.

Syntax:-         string.index(value, start, end)

value

Required. The value to search for

start

Optional. Where to start the search. Default is 0

end

Optional. Where to end the search. Default is to the end of the string

 

txt = “Hello, welcome to my world.”

x = txt.index(“welcome”)

print(x)

output:-

7

txt = “Hello, welcome to my world.”

x = txt.index(“e”)

print(x)

output:-

1

txt = “Hello, welcome to my world.”

x = txt.index(“e”, 5, 10)

print(x)

output:-

8

 

Note:- 1.  Where in the text is the first occurrence of the letter “e”?:

  1. Where in the text is the first occurrence of the letter “e” when you only search between position 5 and 10?:

  2. If the value is not found, the find() method returns -1, but the index() method will raise an exception:

 

txt = “Hello, welcome to my world.”

print(txt.find(“q”))

print(txt.index(“q”))

output:-

-1
Traceback (most recent call last):
  File “demo_ref_string_find_vs_index.py”, line 4 in <module>
    print(txt.index(“q”))
ValueError: substring not found

 

 

error: Content is protected !!