Home > other >  How to remove parts of a str in a list?
How to remove parts of a str in a list?

Time:11-02

I have a variable called data and I would like to remove "//x00" from all of them if they have it. How would I go about doing so? I thought of iterating through all of them and checking each individually, but...

data = ["b'$VNYMR", '-103.322', '-003.191', '-018.818', ' 00.0183', ' 00.0107', ' 00.50\\x0075', '-00.553', ' 03.138', '-09.272', ' 00.000038', '-00.000815', " 00.000183*6F\\x00\\r\\n'"]

for x in data:
    data[x] = data[x].replace('\\x00', '')

CodePudding user response:

When you call for x in data, x is the element in the list, not its index. You could do either

for i, x in enumerate(data):
    data[i] = x.replace('//x00', '')

or

for i in range(len(data)):
    data[i] = data[i].replace('//x00')

You will have to iterate through the list, as it isn't possible to do something for every element in a list without iterating through it at least once.

CodePudding user response:

If you want to remove all occurances, the best option is probably list comprehension

new_data = [i.replace("\\x00", "") for i in data]
  • Related