1

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??

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
RonB7
  • 297
  • 1
  • 4
  • 14

3 Answers3

5

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.

Community
  • 1
  • 1
Thomas Ahle
  • 30,774
  • 21
  • 92
  • 114
1

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
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
0

Alternative solution is to split the string into array:

list(hStr) == hList  


>>> list("hello")
['h', 'e', 'l', 'l', 'o']
Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115