Skip to content Skip to sidebar Skip to footer

Look If A String Starts With The Ending Characters Of Another String?

I want to see if ending of one string is similar to starting of another string if i have a string a='12345678' and b='56789' i want to update a as 123456789 these two strings are

Solution 1:

This works for me:

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

This works even if the string s repeats. What I am doing is going around, for the length of s and then seeing if s[i] is equal to the first char in b. I then look to see if the rest of s is, either b or is in b.

Solution 2:

You can for how long the two match, and concatenate from there:

s="12345678"
b="156789"


longest_match = 0for i inrange(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)

Post a Comment for "Look If A String Starts With The Ending Characters Of Another String?"