Byte string spanning more than one line

2019-07-28 21:30发布

问题:

I need to parse byte string which spans more than one line in the source code. Like this

self.file.write(b'#compdef %s\n\n'
                    '_arguments -s -A "-*" \\\n' % (self.cmdName,))

this line throws the following exception

builtins.SyntaxError: cannot mix bytes and nonbytes literals

which can be fixed in the following way

self.file.write(b'#compdef %s\n\n\'\'_arguments -s -A "-*" \\\n' % (self.cmdName,))

Notice the backslashes after \n. but this fix does the follow the project rules of less than 79 characters per line.

How do I fix this?

The code works fine on Python 2 but fails on Python 3.

回答1:

You are fine to use multiple string literals, but they need to be of the same type. You are missing the b prefix on the second line:

self.file.write(b'#compdef %s\n\n'
                b'_arguments -s -A "-*" \\\n' % (self.cmdName,))

Only when using string literals of the same type will the python parser merge these into one longer bytes string object.

It worked on Python 2 because the b prefix is a no-op; b'..' and '..' produce the same type of object. The b prefix only exists in Python 2 to make it easier to write code for both Python 2 and 3 in the same codebase (polyglot).