假设我有以下两个字符串:"Hey there"
和"there is a ball"
我希望输出为True
,因为第一个以"there"
结尾,第二个以"there"
开头。
另外,如果我知道重叠的长度会很有帮助。
答案 0 :(得分:2)
这应该有效:
def endOverlap(a, b):
for i in range(0, len(a)):
if b.startswith(a[-i:]):
return i
return 0
a = "Hey there"
b = "there is a ball"
c = "here is a ball"
d = "not here is a ball"
print(a, b, endOverlap(a, b))
print(a, c, endOverlap(a, c))
print(a, d, endOverlap(a, d))
编辑:修改后返回重叠长度,并且如果预期只有字符串的一小部分重叠,则效率更高。然后修正了一个错误。
答案 1 :(得分:0)
# do your str checks here...
if (str1.split()[-1] == str2.split()[0]):
答案 2 :(得分:0)
要知道两个字符串的重叠,请使用生成器和endswith
字符串方法。此子字符串的max
值将是最大重叠:
>>> str1 = "Hey there"
>>> str2 = "there is a ball"
>>> overlap = max((str2[:x] for x in range(1,len(str2) + 1) if str1.endswith(str2[:x])),key = len)
>>> overlap
'there'
要返回True
使用if
语句或bool
类型:
>>> if overlap:
... print True
...
True
>>> bool(overlap)
True
要知道长度,只需使用len
函数:
>>> len(overlap)
5