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

Jim jf_byrnes at comcast.net
Wed Jul 25 21:36:41 EDT 2018


On 07/25/2018 07:43 PM, Steven D'Aprano wrote:
> 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

Stephen,

Perfect, thank you.  I did remove the break because I thought I would 
get more than one hit. I got 196, more that I hoped for but now I have a 
better idea of what I am working with.

Regards,  Jim




More information about the Tutor mailing list