[Tutor] How can I find a group of characters in a list of strings?

Steven D'Aprano steve at pearwood.info
Wed Jul 25 20:43:56 EDT 2018


On Wed, Jul 25, 2018 at 06:50:56PM -0500, Jim wrote:
[...]
> I need to check and see if the letters 'OFHCMLIP' are one of the items 
> in the list but there is no way to tell in what order the letters will 
> appear. So I can't just search for the string 'OFHCMLIP'. I just need to 
> locate any strings that are made up of those letters no matter their order.

data = ['MIBMMCCO', 'YOWHHOY', 'ABCDEFG', 'HCMLIPOF', 'TUVWXYZ']

target = sorted('OFHCMLIP')
for pos, item in enumerate(data):
    if sorted(item) == target:
        print("found", pos, item)
        break


-- 
Steve


More information about the Tutor mailing list