【问题标题】:How to find a index of an item in a string?如何在字符串中查找项目的索引?
【发布时间】:2013-11-07 19:09:20
【问题描述】:

但是我需要第二次出现的索引。 就像我有一个字符串“asd#1-2#qwe” 我可以简单地使用 index 方法找到第一个 # 的索引值,即 3。 但是现在我想得到第二个#的索引,应该是7。

【问题讨论】:

    标签: python string python-3.x


    【解决方案1】:

    使用enumeratelist comprehension

    >>> s = "asd#1-2#qwe"
    >>> [i for i, c in enumerate(s) if c=='#']
    [3, 7]
    

    或者如果字符串只包含两个'#',则使用str.rfind

    >>> s.rfind('#')
    7
    

    使用regex:这也适用于重叠的子字符串:

    >>> s = "asd##1-2####qwe"
    >>> import re
    #Find index of all '##' in s
    >>> [m.start() for m in re.finditer(r'(?=##)', s)]
    [3, 8, 9, 10]
    

    【讨论】:

    • 谢谢。两种方式都有用。
    【解决方案2】:

    使用这个:

    s = "asd#1-2#qwe"
    try:
        s.index('#',s.index('#')+1)
    except:
        print "not found"
    

    【讨论】:

      【解决方案3】:

      使用索引方法获取第一次出现的#。如果 index 方法允许一个起始位置,则使用第一个 # + 1 的位置作为起始位置。如果不是,则从第一个 # + 1 的位置开始复制字符串(可能是副本,然后是子字符串)。

      【讨论】:

        【解决方案4】:
        a =  "asd#1-2#qwe"
        
        f = '#'
        
        idx = []
        for i, v in enumerate(a):
            if v == f:
                idx.append(i)
        print idx
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-10-24
          • 1970-01-01
          • 2013-05-08
          • 2016-02-15
          • 2020-12-02
          • 2018-12-23
          相关资源
          最近更新 更多