English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The index() method returns the index value of the substring within the string (if found). If the substring is not found, an exception will be raised.
StringThe syntax of the index() method is:
str.index(sub[, start[, end]])
The index() method takes three parameters:
sub -The substring to be searched for in the string str.
startandend(Optional)-Instr [start:end]中str [start:end]中
index() return value
If the substring exists in the string, it will return the smallest index of the substring found in the string.If the substring does not exist in the string, it will raiseValueError
exception.index() method is similar toIn Python, indexing starts from 0, not
string's find() method-1The only difference is that, if the substring is not found, the find() method returns
Example :index() with only substring parameter result = sentence.index('is fun') print("Substring 'is fun':", result) result = sentence.index('Java')
When running the program, the output is:
print("Substring 'Java':", result) 19 Traceback (most recent call last): File "...", line 6Substring 'is fun': ValueError: substring not found
, inresult = sentence.index('Java') Note:1In Python, indexing starts from 0, not
Example sentence = 'Python programming is fun.' # Search for substring 'gramming is fun.' 10)) # Search for substring 'gramming is ' # Search for substring 'g is' 10, -4)) # Search for substring 'programming' print(sentence.index('fun', 7, 18))
When running the program, the output is:
15 17 Traceback (most recent call last): File "...", line 10, inprint(quote.index('fun', 7, 18)) ValueError: substring not found