['0011111', '0011101', '0011110', '0011110', '0011100', '0010111', '0011000', '0011011', '0011000', '0010001', '0010100', '0010111', '0010110', '0010010', '0001110', '0001110', '0001010', '0001111', '0000111', '0001001', '0000101', '0001000', '0000100', '1000001']
Hi newbie here, how can I change the first index string value "1" in the List, example "1000001" to "0000001". Thanks for solution
CodePudding user response:
If I understand you correctly, if first character of the string in the list is 1
, change it to 0
:
lst = [
"0001000",
"0000100",
"1000001",
]
lst = [f"0{s[1:]}" if s.startswith("1") else s for s in lst]
print(lst)
Prints:
["0001000", "0000100", "0000001"]
EDIT: Using str.replace
:
lst = [s.replace("1", "0", 1) if s.startswith("1") else s for s in lst]
print(lst)
EDIT 2: If you want to change first 1
to 0
(regardless if 1
is found on first place or not you can do):
lst = [
"0001000",
"0000100",
"1000001",
]
lst = [s.replace("1", "0", 1) for s in lst]
print(lst)
Prints:
['0000000', '0000000', '0000001']
CodePudding user response:
Considering that all those strings are binary representations 07bit (maximum value: 127 (0x7F, 0b01111111)), you could do (for each element):
Convert it to an base 2 (unsigned) integer
Bit operation - clearing the MSB is equivalent to anding with 63 (0x3F, 0b00111111)
Convert the resulting integer back to (base 2) string
>>> # Original list >>> l7b = ["0011111", "0011101", "0011110", "0011110", "0011100", "0010111", "0011000", "0011011", "0011000", "0010001", "0010100", "0010111", "0010110", "0010010", "0001110", "0001110", "0001010", "0001111", "0000111", "0001001", "0000101", "0001000", "0000100", "1000001"] >>> l7b_msb_cleared = [f"{int(e, 2) & 0x3F:07b}" for e in l7b] >>> l7b_msb_cleared ['0011111', '0011101', '0011110', '0011110', '0011100', '0010111', '0011000', '0011011', '0011000', '0010001', '0010100', '0010111', '0010110', '0010010', '0001110', '0001110', '0001010', '0001111', '0000111', '0001001', '0000101', '0001000', '0000100', '0000001'] >>> >>> [e == l7b[i] for i, e in enumerate(l7b_msb_cleared)] [True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, False]