The difference between .find() and .index()

Today, when reviewing the basic data type - string, I have a little idea, to summarize:

Definition of string: A string is an ordered set of characters used to store and represent basic textual information.

There are many operations on strings, such as indexing.index(), removing.strip(), replacing.replace(), slicing, etc.

Among them, .index() and .find() are specially taken out to illustrate the difference:

First of all, here is the official explanation:

    S.index(sub[, start[, end]]) -> int
    
    Like S.find() but raise ValueError when the substring is not found.

S.find(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.

You can see that S.index() is similar to S.find(), but an error will be reported if the substring in the index string is not found.

And S.find() will not report an error when the substring is not found, but will return -1

 

Summarize:

s.index(x): Returns the leftmost index value of x in the string, if not, throws a valueError exception

s.find(x) : Returns the index value of the leftmost character where x appears in the string, or -1 if not present

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324600771&siteId=291194637