Python:取两个字符串并仅返回完全匹配的字符和索引

我一直试图从 Pieter Spronck http://www.spronck.net/pythonbook/pythonbook.pdf 的The Coder's Apprentice 中解决这个问题,通过 pdf 第 146 页,或在书中的第 132 页。这是确切的问题:

编写使用两个字符串的代码。对于第一个字符串中在第二个字符串的相同索引处具有完全相同字符的每个字符,您将打印该字符和索引。注意您不会收到“索引越界”运行时错误。用字符串“The Holy Grail”和“Life of Brian”测试它。

我知道有使用 coord 的选项,但到目前为止本书还没有涵盖它,我想以书中提供的可用工具的精确方式学习,以便我能够真正掌握基础知识。

我可以找到匹配的字符及其相应的索引,但我不知道如何只返回完全匹配的字符和索引。我尝试了很多不同的想法,但我似乎无法破解它。我只展示了返回匹配字符及其索引的代码,而不是我尝试过的任何东西,因为它们只是返回错误

谢谢:

def two_string(a, b):
    character = []
    index = []
    for i in a:
        if i in b:
            character.append(i)
    for i in range(len(a)):
        if a[i] in b:
            index.append(i)
    print(character)
    print(index)

two_string('The Holy Grail', 'Life of Brian')

回答

def two_string(a,b):
    for i, (ca, cb) in enumerate(zip(a,b)):
        if ca==cb:
            print(ca, i)


回答

由于只能使用基本功能的限制,您可以执行以下操作:

def two_string(a, b):
  for i in range(min(len(a),len(b))):
    if a[i] == b[i]:
      print(f"Match of character '{a[i]}' found at index {i}")

two_string('The Holy Grail', 'Life of Brian')
# Output: 
# Match of character 'o' found at index 5
# Match of character 'a' found at index 11

  • While using `enumerate` and `zip` is the cleaner and better option, I think this is the most appropriate answer based on the implicit level of knowledge of the OP. Simply find out which of the two strings has the shorter length to avoid IndexError and just compare the individual characters.

以上是Python:取两个字符串并仅返回完全匹配的字符和索引的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>