Python中字符串查找的示例

Joa*_*nge 60 python string find

我试图找一些例子,但没有运气.有谁知道网上的一些例子?我想知道它找不到什么,以及如何从头到尾指定,我猜这将是0,-1.

Pao*_*ino 110

我不确定你在找什么,是什么意思find()

>>> x = "Hello World"
>>> x.find('World')
6
>>> x.find('Aloha');
-1
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但为什么这里-1,而不是索引?我认为 python 更喜欢异常而不是特殊的返回值。 (2认同)
  • find 和 index 是相同的功能,但不匹配时结果不同。Python 通常可能更喜欢异常,但许多用户希望也有一个非异常引发查找索引方法,特别是因为几乎所有其他语言都是这样做的。 (2认同)

Sil*_*ost 43

你也可以使用str.index:

>>> 'sdfasdf'.index('cc')
Traceback (most recent call last):
  File "<pyshell#144>", line 1, in <module>
    'sdfasdf'.index('cc')
ValueError: substring not found
>>> 'sdfasdf'.index('df')
1
Run Code Online (Sandbox Code Playgroud)

  • @Wahnfrieden:使用异常是完全pythonic.当然不值得投票. (10认同)
  • @aehlke实际上,在Python中,使用异常来控制流程是常见的,甚至建议:http://stackoverflow.com/questions/6092992/why-is-it-easier-to-ask-forgiveness-than-permission-in -python,但并非所有的java (8认同)
  • 异常不应用于流量控制.所以,只有在没有匹配的情况下才会使用index(). (7认同)
  • 你为什么选择一个而不是另一个? (4认同)

Phi*_*l H 30

这里:

str.find(sub [,start [,end]])
返回找到substring sub的字符串中的最低索引,这样sub包含在[start,end]范围内.可选参数start和end被解释为切片表示法.如果找不到sub,则返回-1."

所以,举一些例子:

str.find(sub[, start[, end]])
Run Code Online (Sandbox Code Playgroud)


Dan*_*ana 17

老实说,这就是我在命令行上打开Python并开始搞乱的情况:

 >>> x = "Dana Larose is playing with find()"
 >>> x.find("Dana")
 0
 >>> x.find("ana")
 1
 >>> x.find("La")
 5
 >>> x.find("La", 6)
 -1
Run Code Online (Sandbox Code Playgroud)

Python的解释器使这种实验变得容易.(对于具有类似翻译的其他语言也是如此)


Luc*_*ovo 6

如果要在文本中搜索字符串的最后一个实例,可以运行rfind.

例:

   s="Hello"
   print s.rfind('l')
Run Code Online (Sandbox Code Playgroud)

输出:3

*无需进口

完整语法:

stringEx.rfind(substr, beg=0, end=len(stringEx))
Run Code Online (Sandbox Code Playgroud)