Reputation: 59
I am trying to find code that will allow to find a common ending between two strings, for example:
s1 = 'running'
s2 = 'ruminating'
and the output would result in:
'ing'
It must be specifically for the ending of the string but i am not sure how to do this
Upvotes: 2
Views: 573
Reputation: 164673
You can write a function and iterate:
s1 = 'running'
s2 = 'ruminating'
def get_common(s1, s2):
L = []
for i, j in zip(s1[::-1], s2[::-1]):
if i != j:
break
L.append(i)
return ''.join(L[::-1])
common = get_common(s1, s2) # ing
Upvotes: 0
Reputation: 362716
The stdlib already has commonprefix
:
>>> strings = ['running', 'ruminating']
>>> from os.path import commonprefix
>>> commonprefix(strings)
'ru'
It's easily adapted for your needs:
>>> commonprefix([s[::-1] for s in strings])[::-1]
'ing'
Upvotes: 1