hello,

I want to compare 2 strings.I want to find if a list with characters contains all the letters in a string.
If all the letters in the string are in the list.

For example:

mystring='abc'
mylist=['a','b','c'] must return True

mystring='abc'
mylist=['a','c','b'] must return True

mystring='abc'
mylist=['a','f','c'] must return False

I am trying:

for i in range(len(mylist)):
        if mylist[i] in mystring:
            return True  
        else:
            return False

but it doesn't work as expected.I can't isolate every letter.

Recommended Answers

All 7 Replies

Also, how to deal with an empty string or list?

Adding if mylist: and return False doesn't seem to work.

for i in range(len(mylist)):
    if mylist:
        if mylist[i] in mystring:
            return True
        else:
            return False
    else:
        return False

Use "if len(a_list)". Also this is what sets are for
if set(a_list).issubset(set(a_string)) ## if all list is in string

I think if mylistis the same as if len(mylist) ?
Also, what about the initial problem?

This should work:

def is_string_in_list(mystring, mylist):
    for c in mystring:
        if c not in mylist:
            return False
    return True


# short test
mylist = ['a', 'b', 'c']
mystring = 'acb'
print(is_string_in_list(mystring, mylist))  # True

mystring = 'afc'
print(is_string_in_list(mystring, mylist))  # False

Yes!Ok, thanks!

Just FYI, when you need to access both the index and value in an interation, consider using "enumerate":

In [1]: mylist = ['foo', 'bar', 'baz']

In [2]: for idx, value in enumerate(mylist):
   ...:     print idx, value
   ...:     
0 foo
1 bar
2 baz

Ok,thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.