【问题标题】:python find method doesn't work for "/" herepython find方法不适用于“/”这里
【发布时间】:2014-06-18 03:42:08
【问题描述】:

考虑下面的代码

#!/usr/bin/python
url = "http://stackoverflow.com/questions/22389923/python-find-method-doesnt-work-for-here"
print url.find("/",8)

你将得到的输出是 24,但答案肯定是 3。不是吗?

【问题讨论】:

标签: python python-2.7


【解决方案1】:

这会找到子字符串 / 的第一个 索引从索引 8 开始搜索

您可能认为它是在计算出现次数,而不是查找位置,但如果您阅读文档字符串,您不会误解这一点:

Docstring:
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.

现在,我想你可能正在寻找“3”:

>>> url[8:].count('/')
3

【讨论】:

  • @user3393168 str.find 返回索引,而不是计数。
【解决方案2】:

您误解了str.find 的用法。它找到某个子字符串的index(即它的位置),而不是它出现的次数,就像你想要的那样。您想使用(惊喜,惊喜)str.count

例如:

>>> url = "http://stackoverflow.com/questions/22389923/python-find-method-doesnt-work-for-here"
>>> url.count('/', 8)
3

这似乎是您想要的输出。

【讨论】:

    【解决方案3】:

    输出是正确的,你为什么期待3?看:

    http://stackoverflow.com/questions/22389923/python-find-method-doesnt-work-for-here
    ^  ^    ^               ^
    0  3    8              24
    

    根据documentationurl.find("/", 8) 正在寻找"/" 第一次出现的索引第8 个索引之后,而这恰好在第24 个索引中。引用文档(强调我的):

    string.find(s, sub[, start[, end]])
    

    返回 s 中找到子字符串 sub 的最低 index,使得 sub 完全包含在s[start:end]。失败时返回-1startend 的默认值以及负值的解释与切片相同。

    也许您打算使用count

    url.count('/', 8)
    => 3
    

    【讨论】:

      【解决方案4】:

      Python 中的find 方法返回字符串中特定字符的索引。可选参数之一是要开始的字符串中的位置。在你的命令中,你说:

      print url.find("/", 8)
      

      您告诉它打印第一次出现斜线的索引,从第 8 个字符开始。在这个字符串中,出现在第 24 个字符上。

      来自文档:

      string.find(s, sub[, start[, end]])
      
      Return the lowest index in s where the substring sub is found such that sub 
      is wholly contained in s[start:end]. Return -1 on failure. Defaults for start 
      and end and interpretation of negative values is the same as for slices.
      

      更多的文档在这里:http://docs.python.org/2/library/string.html#string.find

      您似乎是在尝试查找某个字符在起点之后出现的次数。为此,您可以使用.count 方法。这是一些示例代码

      #!/usr/bin/python
      url = "http://stackoverflow.com/questions/22389923/python-find-method-doesnt-work-for-here"
      print url.count( '/', 8)
      # should print 3
      

      更多的文档在这里:http://docs.python.org/2/library/string.html#string.count

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-30
        • 1970-01-01
        • 1970-01-01
        • 2015-02-26
        • 1970-01-01
        • 1970-01-01
        • 2016-04-13
        • 1970-01-01
        相关资源
        最近更新 更多