pythonlistbinary-string

Python: Access elements of a binary string as if there are no spaces between


I have a list of couple like this ('01 0 00 0',key0), ('01 0 11 0',key1), ('01 0 11 1',key2) and I would like to pick the elements with only the third and fourth bit equal to 1. So for example in this case I'll get ('01 0 11 0',key1) and ('01 0 11 1',key2).

How can I pick the couple with these elements ?


Solution

  • You can use a list comprehension:

    l = [i for i in list_couples if i[0].split(" ")[2]=="11"]
    

    If the spaces are not always the same:

    l = [i for i in list_couples if i[0].replace(" ", "")[3:5]=="11"]