【问题标题】:Given 2 strings find the indexes where one string occurs in another [duplicate]给定2个字符串,找到一个字符串出现在另一个字符串中的索引[重复]
【发布时间】:2013-05-07 08:57:51
【问题描述】:

正如标题所说,我有 2 个字符串,例如:

string = """
for i in x:
    for y in z[i]:
        print y
"""
s2 = "for"

我想得到的是:

[1, 17] # positions where "for" starts in string..

是否有任何内置功能,或者比多个finds 更好的方法??

【问题讨论】:

  • @AshwiniChaudhary 我刚刚对我自己的问题投了赞成票..
  • 我很高兴我的答案与那里接受的答案相呼应! :-) 我不知道另一个问题的存在。
  • @MartijnPieters 没关系,我也做过一次... ;)

标签: python string find


【解决方案1】:

您要么使用多个查找,要么使用正则表达式和re.finditer()

[match.start() for match in re.finditer(re.escape(s2), string)]

re.finditer() 产生match objects,我们在这里使用re.MatchObject.start() method 来挑选找到的匹配项的开始索引。

我使用re.escape() 来防止s2 中的正则表达式元字符被解释以确保行为与多个str.find() 调用相同。

演示:

>>> import re
>>> string = """
... for i in x:
...     for y in z[i]:
...         print y
... """
>>> s2 = "for"
>>> [match.start() for match in re.finditer(re.escape(s2), string)]
[1, 17]

【讨论】:

  • 这比多次查找要好..
猜你喜欢
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 2011-03-25
  • 2015-07-10
  • 2021-11-28
  • 2016-07-27
  • 1970-01-01
相关资源
最近更新 更多