RonB7
RonB7

Reputation: 297

Comparing a string to a list of characters

Say I have a list of characters ['h','e','l','l','o'] and I wanted to see if the list of characters match a string 'hello', how would I do this? The list needs to match the characters exactly. I thought about using something like:

hList = ['h','e','l','l','o']
hStr = "Hello"
running = False

if hList in hStr :
  running = True
  print("This matches!") 

but this does not work, how would I do something like this??

Upvotes: 1

Views: 113

Answers (3)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160667

Or, another way is the reverse of what the other answer suggests, create a list out of hStr and compare that:

list(hStr) == hList

Which simply compares the lists:

list('Hello') == hList
False

list('hello') == hList
True

Upvotes: 1

Krzysztof Krasoń
Krzysztof Krasoń

Reputation: 27516

Alternative solution is to split the string into array:

list(hStr) == hList  


>>> list("hello")
['h', 'e', 'l', 'l', 'o']

Upvotes: 0

Thomas Ahle
Thomas Ahle

Reputation: 31624

You want ''.join(hList) == hStr.

That turns the list into a string, so it can be easily compared to the other string.

In your case you don't seem to care about case, so you can use a case insensitive compare. See How do I do a case insensitive string comparison in Python? for a discussion of this.

Upvotes: 5

Related Questions