Comparing a string to a sequence of chars

Viewed 71

I have the following string

"long"

And I have an array of chars that will contain the sequence [..., [l],[o],[n],[g],...] somewhere in it. Can someone help me find a way to compare the string to the array of chars and return a True or False without having to join the array into one string?

Thanks!

2 Answers

You can do this:

s = 'long'
lst = [['a'],['l'],['o'],['n'],['g'],['z']]

p = [[x] for x in s]
any([p==lst[i:i+len(p)] for i in range(0, len(lst)-len(p))])

Out[81]: True

Question in comment: "How to get the index of first match?"

[j for j, i in enumerate(range(0, len(lst)-len(p))) if p==lst[i:i+len(p)]][0]

Out[83]: 1

I won't claim you should do it this way, but you certainly could.

z = "long"
a = [letter for letter in z]
b = ['l', ' ', 'x', 4, 'l', 'o', 'n', 'g', 5]
for i, j in enumerate(b):
    if a == b[i:i+len(a)]:
        print('"{}" found at index {}'.format(z,i))

Effectively we explode the string and then create slices of the list for comparison to the exploded string.

Related