Richard Harvie
Richard Harvie

Reputation: 95

How to create zero string of defined length in Python 2.x

I want to create a string of 1024 zero bytes in Python 2.7

I know in Python 3.x I can just do data = bytes(1024) but in Python 2.7 that is just an alias for str which therefore creates a string of '1024'

This is part of a system that generates a data file on the fly via django - and the header needs to include an area of zero padding. Our server is stuck on Python 2.7.

Upvotes: 0

Views: 48

Answers (1)

user2357112
user2357112

Reputation: 281584

You can probably use a bytearray instead:

data = bytearray(1024)

but if you need a bytes object (you probably don't), you can convert to bytes:

data = bytes(bytearray(1024))

Upvotes: 1

Related Questions