python find( )方法

Python012

python find( )方法,第1张

Python中的find( )方法

用于检验字符串是否包含子字符串str,如果已指定beg和end范围,则检验将在制定范围内。

如果包含字符串,返回开始的索引值,否则返回-1。

语法:str.find(str,beg=0,end=len(string))

str——指定检索的字符串

beg——开始索引,默认为0

end——结束索引,默认为字符串的长度

find()函数找不到时返回为-1。

python中遇到不明白的地方,可以试试help

这里要查看find的作用,可以键入help(str.find),然后得到提示如下:

Help on method_descriptor:

find(...)

    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.

解释要点大致如下:

find()方法检测字符串S中是否包含子字符串sub,如果指定start(开始) 和 end(结束)范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值(如果包含多个字串,只返回最左边出现的索引值),查找失败返回-1。以本题为例:

s="abcd1234"

s.find("cd"),在字符串s中查找字串"cd"第一次出现时s中的索引值,因为索引从0开始,所以结果为2,注意s中出现多次cd的情况,例如:

s="abcd1234cd"

s.find("cd")的结果依然是2,找不到时返回-1,比如:

s="1234"

s.find("cd")的结果为-1

题主最好给出一个稍微具体点的应用场景,可能有更加优化的方法。 我自己构造一个简单的例子如下: matlab: A = find(B>0) python: A = [i for i in range(len(B)) if B[i]>0] 另外注意,matlab里的数组索引从1开始,和python不同。