Best way to replace \ x00 in python lists?

I have a list of values ​​from a parsed PE file that includes / x 00 zero bytes at the end of each section. I want to remove / x 00 bytes from a string without deleting all "x" from the file. I tried doing .replace and re.sub, but not that success.

Using Python 2.6.6

Example.

import re

List = [['.text\x00\x00\x00'], ['.data\x00\x00\x00'], ['.rsrc\x00\x00\x00']]

while count < len(List):
    test = re.sub('\\\\x00', '', str(list[count])
    print test
    count += 1

>>>tet  (removes x, but I want to keep it)
>>>data
>>>rsrc

I want to get the following output

text data rsrc

Any ideas on a better way around this?

+5
source share
6 answers
>>> L = [['.text\x00\x00\x00'], ['.data\x00\x00\x00'], ['.rsrc\x00\x00\x00']]
>>> [[x[0]] for x in L]
[['.text\x00\x00\x00'], ['.data\x00\x00\x00'], ['.rsrc\x00\x00\x00']]
>>> [[x[0].replace('\x00', '')] for x in L]
[['.text'], ['.data'], ['.rsrc']]

Or change the list in place instead of creating a new one:

for x in L:
    x[0] = x[0].replace('\x00', '')
+6
source
lst = (i[0].rstrip('\x00') for i in List)
for j in lst: 
   print j,
+5
source

, , '\x00' .

, Python 2 non-Unicode translate() ( ) 8- , . ( Python 3, Unicode.)

List , , . , sections, "" PEP 8 - Python Code.

sections = [['.text\x00\x00\x00'], ['.data\x00\x00\x00'], ['.rsrc\x00\x00\x00']]

for section in sections:
    test = section[0].translate(None, '\x00')
    print test

:

.text
.data
.rsrc
+1
from itertools import chain

List = [['.text\x00\x00\x00'], ['.data\x00\x00\x00'], ['.rsrc\x00\x00\x00']]    
new_list = [x.replace("\x00", "") for x in chain(*List)]
#['.text', '.data', '.rsrc']
0

, :

re.sub(u'\x00', '', s)

:

l = [['.text\x00\x00\x00'], ['.data\x00\x00\x00'], ['.rsrc\x00\x00\x00']]
for x in l:
    for s in l:
        print re.sub(u'\x00', '', s)
        count += 1

.text
.data
.rsrc

, :

[[re.sub(u'\x00', '', s) for s in x] for x in l]

, "u" . :

'\x00'
0

I think the best way to take care of this particular problem is to use the following function:

import string

for item  in List:
  filter(lambda x: x in string.printable, str(item))

This will get rid of not only \ x00, but any other such hexadecimal values ​​that are added to your string.

0
source

All Articles