array x contains string followed by all zeros. I need expand the string but keep x array’s size the same.
e.g.:
JavaScript
x
11
11
1
def modify(x,y):
2
return x
3
4
# input x and y
5
x = bytes([0x41,0x42,0x43,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00])
6
y = 'EFGH'
7
print(x)
8
x = modify(x,y)
9
#output x
10
print(x)
11
expected output:
JavaScript
1
3
1
b'ABCDx00x00x00x00x00x00x00x00x00x00x00x00'
2
b'ABCDEFGHx00x00x00x00x00x00x00x00'
3
What’s propery way to do it in python3?
Advertisement
Answer
You can use ljust
to add a number of characters to make the resulting bytes
the length you want:
JavaScript
1
3
1
>>> b'ABCD'.ljust(20, b'')
2
b'ABCDx00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00'
3
So, all in all: strip the trailing zeroes out of the source bytes, add in the bit you want to add, re-pad back to the original length:
JavaScript
1
6
1
>>> x = bytes([0x41,0x42,0x43,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00])
2
>>> y = b'EFGH'
3
>>> (x.rstrip(b"x00") + y).ljust(len(x), b"x00")
4
b'ABCDEFGHx00x00x00x00x00x00x00x00'
5
>>>
6