Byte string spanning more than one line

心不动则不痛 提交于 2019-12-11 11:32:55

问题


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).



来源:https://stackoverflow.com/questions/38326297/byte-string-spanning-more-than-one-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!