Home >Backend Development >Python Tutorial >How to use index in python

How to use index in python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-21 11:24:1520376browse

The index() method in Python detects whether the substring str is included in the string. If the beg (start) and end (end) ranges are specified, check whether it is included in the specified range. This method is the same as the python find() method. The same, except that if str is not in string, an exception will be reported.

How to use index in python

Syntax

index() method syntax:

str.index(str, beg=0, end=len(string))

Parameters

str -- Specify the retrieved string beg -- Start index, default is 0. end – end index, defaults to the length of the string.

Related recommendations: "python video tutorial"

Return value

If it contains a substring, return the starting index value , otherwise an exception is thrown.

Examples

The following examples show examples of the index() method:

#!/usr/bin/python
str1 = "this is string example....wow!!!";
str2 = "exam"; 
print str1.index(str2);
print str1.index(str2, 10);
print str1.index(str2, 40);

The output results of the above examples are as follows:

15
15
Traceback (most recent call last):
  File "test.py", line 8, in 
  print str1.index(str2, 40);
ValueError: substring not found

shell returned 1

The above is the detailed content of How to use index in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn