【问题标题】:How do i find the position of MORE THAN ONE substring in a string (Python 3.4.3 shell)如何在字符串中找到多个子字符串的位置(Python 3.4.3 shell)
【发布时间】:2016-02-02 20:33:59
【问题描述】:

以下代码显示“word”在字符串中出现一次时的位置。如何更改我的代码,以便如果“单词”在字符串中出现多次,它将打印所有位置?

string = input("Please input a sentence: ")
word = input("Please input a word: ")
string.lower()
word.lower()
list1 = string.split(' ')
position = list1.index(word)
location = (position+1)
print("You're word, {0}, is in position {1}".format (word, location))

【问题讨论】:

  • 实际上它在列表中的位置,因为您将字符串按单词拆分为列表

标签: python string python-3.x indexing position


【解决方案1】:

使用enumerate:

[i for i, w in enumerate(s.split()) if w == 'test']

例子:

s = 'test test something something test'

输出:

[0, 1, 4]

但我想这不是您要找的,如果您需要字符串中单词的起始索引,我建议使用 re.finditer:

import re

[w.start() for w in re.finditer('test', s)]

同样s 的输出将是:

[0, 5, 30]

【讨论】:

    【解决方案2】:
    sentence = input("Please input a sentence: ")
    word = input("Please input a word: ")
    sentence = sentence.lower()
    word = word.lower()
    wordlist = sentence.split(' ')
    print ("Your word '%s' is in these positions:" % word)
    for position,w in enumerate(wordlist):
        if w == word:
            print("%d" % position + 1)
    

    【讨论】:

      【解决方案3】:

      另一种不会在空间上拆分的解决方案。

      def multipos(string, pattern):
      
          res = []
          count = 0
          while True:
              pos = string.find(pattern)
              if pos == -1:
                  break
              else:
                  res += [pos+count]
                  count += pos+1
                  string = string[pos+1:]
      
          return res
      
      
      test = "aaaa 123 bbbb 123 cccc 123"
      res = multipos("aaaa 123 bbbb 123 cccc 123", "123")
      print res
      for a in res:
          print test[a:a+3]
      

      还有脚本输出:

      % python multipos.py
      [5, 14, 23]
      123
      123
      123
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-02
        • 2012-05-21
        • 1970-01-01
        • 2014-05-06
        • 2021-05-24
        • 1970-01-01
        相关资源
        最近更新 更多