2

I have a list of bytes strings that I try for format into another string, which in turn I convert to bytes, looks something like this:

byte_string = b'text' fmt = 'this is the text: %s' fmt_string = bytes(fmt % byte_string, 'utf-8') 

but if I print fmt_string I get this

b"this is the text: b'text'"

I know that in python3.5 I can do this:

b'this is the text: %s' % b'text' 

and receive:

b'this is the text: text'

is there a way to do the same with python3.4?

1 Answer 1

2

You can't use formatting on bytes objects in Python 3.4 or below. Your options are to upgrade to 3.5 or newer, or not use formatting on bytes.

In Python 3.5 and up, you need to make fmt a bytes object; you'd use a bytes literal, and apply the % operator to that:

fmt = b'this is the text: %s' fmt_string = fmt % byte_string 

Alternatively, encode the template first, then apply the values:

fmt = 'this is the text: %s' fmt_string = bytes(fmt, 'utf-8') % byte_string 

If upgrading is not an option, but your bytes values have a consistent encoding, decode first, then encode again:

fmt = 'this is the text: %s' fmt_string = bytes(fmt % byte_string.decode('utf-8'), 'utf-8') 

If you can't decode your bytes values, then your only remaining option is to concatenate bytes objects:

fmt = b'this is the text: ' # no placeholder fmt_string = fmt + byte_string 

This will require multiple parts if there is text after the placeholders, of course.

Sign up to request clarification or add additional context in comments.

2 Comments

python3.4 doesn't let you format into bytes object: fmt = b'the text is: %s' fmt % b'text' --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-21-114011e9215e> in <module>() ----> 1 fmt % b'text' TypeError: unsupported operand type(s) for %: 'bytes' and 'bytes'
Oh crumbs. In that case your options are to using grade to 3.5, or decode both the format and value, interpolate then reencode, or to not use formatting (use concatenation instead).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.