1

I am fairly new to python and I am trying to figure out how to find if the elements of a list equal a given string?

lists=["a","b",'c']
str1='abc'

I know it is probably easy, but I am having a hard time without using string methods.

Thanks, DD

0

3 Answers 3

2
>>> l = ['a', 'b', 'c']
>>> l == list('abc')
True

But, if the order of items in the list can be arbitrary, you can use sets:

>>> l = ['c', 'b', 'a']
>>> set(l) == set('abc')
True

or:

>>> l = ['c', 'b', 'a']
>>> s = set(l)
>>> all(c in s for c in 'abc')
True
Sign up to request clarification or add additional context in comments.

Comments

1
>>> lists=["a","b",'c']
>>> str1='abc'
>>> ''.join(lists) == str1
True

Comments

0

you can use .join to create a string from your list:

list = ['a', 'b', 'c']
strToComapre = ''.join(list1)

Now you can check if strToComapre is "in" the original str:

if strToCompare in originalStr:
    print "yes!"

If you want a pure compare use:

if strToCompare == originalStr:
    print "yes! it's pure!"

There are lots of options in python i'll add some other useful posts:

Compare string with all values in array

http://www.decalage.info/en/python/print_list

2 Comments

Don't compare strings using is. Sometimes it works thanks to string interning, but == is what really works.
You are right, the post was edited 'is' will do the trick for identities in a simple compare '==' its the best to use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.