In advance, I have searched for a solution to this problem already but there does not seem to be one in existence. So I am currently trying to self teach python by running through the Python "Path" on http://singpath.appspot.com and I ran into a problem I do not understand how to solve. I have tried multiple different ways to solve it but keep coming up with different incorrect results. Any hints/help would be spectacular! Thanks in advance!
Question:
Comparing Strings
Create a function that takes an input of two strings
and returns a string that contains all of the characters that appear
in both of the inputs. The result should not have any repeats and
should be listed in sorted order. You might want to use the
variable lowercase from the string module so that you have all the
letters in order.
My Current Code:
def in_both(s1, s2):
s1 = s1.lower()
s2 = s2.lower()
l1=list(''.join(s1.split()))
l2=list(''.join(s2.split()))
same = ''
for i in l1:
if i in l2:
same = ''.join(i)
return same
Example:
call: in_both('apple','orange') recieved: 'e' expected: 'ae'
As you can see it is only collecting a single similar character. Any suggestions? I’ve tried a couple of different things but I am unsure where to go from here! Please help!
P.s. I got the list idea from a similar question located here: Python Function to return a list of common letters in first and last names
I understand how it works the problem is I have to return a string with all comparisons at the same time. Thanks ‘the wolf’ for the idea for the list(s) of characters.
You can get unique characters in any string by turning it into a set.
The you can get the intersection of two sets using
intersection.And you can sort the result, which returns a list.