Skip to content Skip to sidebar Skip to footer

Check If String Ends With The Beginning Of Another String

Let's say I have the following two strings: 'Hey there' and 'there is a ball' I want the output to be True, because the first one ends with 'there' and the second one begins with '

Solution 1:

This should work:

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))

Edit: modified to return length of overlap and to be more efficient if only small parts of the string are expected to overlap. Then fixed a bug.

Solution 2:

# do your str checks here...if (str1.split()[-1] == str2.split()[0]):

Solution 3:

To know overlap of two strings use generator and endswith string method. The max value of this substring will be the max overlap:

>>>str1 = "Hey there">>>str2 = "there is a ball">>>overlap = max((str2[:x] for x inrange(1,len(str2) + 1) if str1.endswith(str2[:x])),key = len)>>>overlap
'there'

To return True use if statements or bool type:

>>>if overlap:...printTrue... 
True
>>>bool(overlap)
True

To know the length just use len function:

>>>len(overlap)
5

Post a Comment for "Check If String Ends With The Beginning Of Another String"