【问题标题】:Look if a string starts with the ending characters of another string?查看一个字符串是否以另一个字符串的结尾字符开头?
【发布时间】:2019-09-04 19:32:21
【问题描述】:

我想看看一个字符串的结尾是否与另一个字符串的开头相似

如果我有一个字符串 a="12345678"b="56789" 我想将 a 更新为 123456789

这两个字符串在一个列表中

s="12345678"
b="56789"

o/p:

s=123456789

【问题讨论】:

标签: python python-3.x


【解决方案1】:

这对我有用:

s="12345678"
b="56789"
for i in range(len(s)):
    if s[i] == b[0]:
        if s[i::] in b[0:len(s[i::])]:
            print('Found')

即使字符串 s 重复,这也有效。我正在做的是围绕s 的长度,然后查看s[i] 是否等于b 中的第一个字符。然后我看看s 的其余部分是b 还是b

【讨论】:

  • Noobie(也不是 OP)但是第二个 if 语句(s[i::])中的切片是什么类型的
【解决方案2】:

您可以将两者匹配多长时间,然后从那里连接:

s="12345678"
b="156789"


longest_match = 0
for i in range(1, min(len(s), len(b))):
    if s[-i:] == b[:i]:
        longest_match = i

if longest_match > 0:
    o = s + b[longest_match:]
    print(o)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-04
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 2011-06-13
    • 2012-02-09
    相关资源
    最近更新 更多