YouTip LogoYouTip

Python3 String Index

# Python3.x Python3 index() Method [![Image 3: Python3 Strings](#) Python3 Strings](#) * * * ## Description The `index()` method checks if a substring `str` is contained within a string. If the optional `beg` (start) and `end` (end) range is specified, it checks if the substring is within that range. This method is similar to the `find()` method, except that it raises an exception if `str` is not found in the string. ## Syntax The syntax for the `index()` method is: str.index(str, beg=0, end=len(string)) ## Parameters * `str` -- The substring to search for. * `beg` -- The starting index to begin the search. Default is 0. * `end` -- The ending index to stop the search. Default is the length of the string. ## Return Value If the substring is found, it returns the index of the first occurrence. Otherwise, it raises a `ValueError` exception. ## Example The following examples demonstrate the use of the `index()` method: #!/usr/bin/python3 str1 = " example....wow!!!" str2 = "exam";print (str1.index(str2))print (str1.index(str2, 5))print (str1.index(str2, 10)) The output of the above example is as follows (an exception message will appear if the substring is not found): 77Traceback (most recent call last): File "test.py", line 8, in print (str1.index(str2, 10))ValueError: substring not found **Note:** In the following chapters, we will provide a detailed introduction to the use of Python Exceptions. * * Python3 Strings](#)
← Git InitTs Map β†’