【问题标题】:Find all the occurrences of a character in a string查找字符串中出现的所有字符
【发布时间】:2012-10-12 03:49:10
【问题描述】:

我试图找出所有出现的“|”在一个字符串中。

def findSectionOffsets(text):
    startingPos = 0
    endPos = len(text)

    for position in text.find("|",startingPos, endPos):
        print position
        endPos = position

但我得到一个错误:

    for position in text.find("|",startingPos, endPos):
TypeError: 'int' object is not iterable

【问题讨论】:

标签: python string


【解决方案1】:

功能:

def findOccurrences(s, ch):
    return [i for i, letter in enumerate(s) if letter == ch]


findOccurrences(yourString, '|')

将返回出现| 的yourString 的索引列表。

【讨论】:

  • 这个循环是如何工作的? i for i, letter in enumerate(s) if letter == ch.
  • @Goodword:这个答案使用了列表理解;见Python tutorial。
  • 函数在定义行拼写错误。它应该是带有两个 r 的“def findOccurrences”。
【解决方案2】:

如果你想索引字符串中所有出现的| 字符,你可以这样做

import re
str = "aaaaaa|bbbbbb|ccccc|dddd"
indexes = [x.start() for x in re.finditer('\|', str)]
print(indexes) # <-- [6, 13, 19]

你也可以

indexes = [x for x, v in enumerate(str) if v == '|']
print(indexes) # <-- [6, 13, 19]

【讨论】:

    【解决方案3】:

    这里用正则表达式比较容易;

    import re
    
    def findSectionOffsets(text):
        for m in re.finditer('\|', text):
            print m.start(0)
    

    【讨论】:

      【解决方案4】:
      import re
      def findSectionOffsets(text)
          for i,m in enumerate(re.finditer('\|',text)) :
              print i, m.start(), m.end()
      

      【讨论】:

        【解决方案5】:

        text.find 返回一个整数(找到所需字符串的索引),因此您可以对其运行 for 循环。

        我建议:

        def findSectionOffsets(text):
            indexes = []
            startposition = 0
        
            while True:
                i = text.find("|", startposition)
                if i == -1: break
                indexes.append(i)
                startposition = i + 1
        
            return indexes
        

        【讨论】:

        • 我认为这行不通,因为 startposition 永远不会改变 - 如果匹配,它将永远循环。
        【解决方案6】:

        如果text 是您要计算其中包含多少"|" 的字符串,则以下代码行将返回计数:

        len(text.split("|"))-1
        

        注意:这也适用于搜索子字符串。

        【讨论】:

          【解决方案7】:

          text.find() 只返回第一个结果,然后你需要根据它设置新的起始位置。像这样:

          def findSectionOffsets(text):
              startingPos = 0
          
              position = text.find("|", startingPos):
              while position > -1:
                  print position
                  startingPos = position + 1
                  position = text.find("|", startingPos)
          

          【讨论】:

          • 无限循环
          • 谢谢,应该修好了!
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-03-22
          • 1970-01-01
          • 1970-01-01
          • 2012-11-15
          相关资源
          最近更新 更多