【问题标题】:Is there a way to determine the indices where a python string differs from another string?有没有办法确定 python 字符串与另一个字符串不同的索引?
【发布时间】:2020-05-29 11:42:52
【问题描述】:

我进行了广泛的搜索,似乎找不到任何可以做到这一点的预建库:

给定python中的2个字符串,其中一个是原始字符串,另一个是某些单词被占位符替换,我想确定原始字符串中已被占位符替换的单词的索引。

例子:

original = "This is the original string"

processed = "This is [placeholder] string"

indices = [8, 20]

第一个索引是被替换的子串的开始,第二个索引是这个子串的结束。

任何帮助将不胜感激。

【问题讨论】:

标签: python string replace


【解决方案1】:

这可能不是我编写的最漂亮的 Python 代码,但它会起作用:

first = [index for index, 
        (a, b) in enumerate(zip(list(original), 
        list(processed))) if a != b ][0]

second = [len(original) - index for index, 
         (a, b) in enumerate(zip(list(original[::-1]), 
         list(processed[::-1]))) if a != b ][0]

difference = [first, second]

它返回存在不一致的第一个索引。反过来也一样。

Out[76]: [8, 20]

更详细的:

  1. 比较每个字母,它返回first != second 所在的第一个索引
  2. 从末尾开始比较每个字母,返回len(first) - first difference
  3. 它创建这两个索引的列表

【讨论】:

  • 我忘了提到文本中可能有多个占位符,在这种情况下您的解决方案不会这样做。
猜你喜欢
  • 1970-01-01
  • 2011-12-04
  • 2015-09-25
  • 2019-09-30
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-05
相关资源
最近更新 更多