Reputation: 203
Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive").
Examples / Tests:
>>> end_other('Hiabc', 'abc')
True
>>> end_other('AbC', 'HiaBc')
True
>>> end_other('abc', 'abXabc')
True
My Code:
def end_other(s1, s2):
s1 = s1.upper()
s2 = s2.upper()
if s1[2:6] == s2:
return True
elif s2[2:6] == s1:
return True
elif s2 == s1:
return True
else:
return False
What I expect is wrong.
(NB: this is a code practice from CodingBat
Upvotes: 1
Views: 1277
Reputation: 251116
something like this, using str.rfind()
:
In [114]: def end(s1,s2):
s1=s1.lower()
s2=s2.lower()
if s1 in s2 and s2.rfind(s1)+len(s1) == len(s2):
return True
elif s2 in s1 and s1.rfind(s2)+len(s2) == len(s1):
return True
return False
.....:
In [115]: end('Hiabc','abc')
Out[115]: True
In [116]: end('abC','HiaBc')
Out[116]: True
In [117]: end('abc','abxabc')
Out[117]: True
In [118]: end('abc','bc')
Out[118]: True
In [119]: end('ab','ab12')
Out[119]: False
Upvotes: 0
Reputation: 1432
Any reason you can't use the built-in functions?
def end_other(s1, s2):
s1 = s1.upper()
s2 = s2.upper()
return s1.endswith(s2) or s2.endswith(s1)
Your code with the arbitrary slices doesn't make a lot of sense.
Upvotes: 7