【问题标题】:Comparing specific characters in strings比较字符串中的特定字符
【发布时间】:2015-04-07 03:18:23
【问题描述】:
s1="aaaaa"
s2="aa"
#expected output=3, because there is a "aa" in "aaaaa", at the 3rd position of s2

如何找到字符匹配的最后位置?

【问题讨论】:

  • 上述示例的预期输出是什么?
  • 你想要什么结果?
  • 您的问题应该是“查找 s1 中与 s2 中所有字符匹配的所有字符的索引”
  • 哇,这个问题一直在发生巨大变化。

标签: python string-comparison


【解决方案1】:

听起来您在描述方法str.rfind(),它是标准库的一部分。

>>> 'aaaaa'.rfind('aa')
3

【讨论】:

  • 你忘了字符 'h' 我可以在两个字符串中看到 'h'
  • 当它是 ("aaaaa","aa") 它应该返回 3 但它返回 4
【解决方案2】:
[pos for pos, match in enumerate(c1 == c2 for c1, c2 in zip(s1, s3)) if match]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-22
    • 2015-07-15
    • 2012-05-16
    • 2015-11-06
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多