I have to translate a java lib into a python one.
During that process i came across the arrays.copyOf() function (the one for bytes not string).
From Docs:
public static byte[] copyOf(byte[] original, int newLength)
Returns: a copy of the original array, truncated or padded with zeros to obtain the specified length
I would like to know if there is a built in equivalent of it or if there is a lib that does it.
my_data[some_int:some_int]
is the equivalent of java copyOfRange()
Here I need to output specific length bytes or byte array that will be padded with 0 if too short
CodePudding user response:
We can do this in two steps,
- Create a copy of the given list.
- We can use slice assignment to return a list of size specified by the second arg.
def copy_of(lst, length):
out = lst.copy() # This is a shallow copy.
# For deepcopy use `copy.deepcopy(lst)`
out[length:] = [0 for _ in range(length - len(lst))]
return out
l = [1, 2, 3]
print(copy_of(l, 5))
# [1, 2, 3, 0, 0]
print(copy_of(l, 2))
# [1, 2]