字节字符串跨越多行 [英] Byte string spanning more than one line

查看:206
本文介绍了字节字符串跨越多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析跨越源代码中多行的字节字符串.像这样

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

此行引发以下异常

builtins.SyntaxError: cannot mix bytes and nonbytes literals

可以通过以下方式修复

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

注意\n之后的反斜杠.但是此修复程序确实遵循了每行少于79个字符的项目规则.

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

我该如何解决?

该代码在Python 2上工作正常,但在Python 3上失败.

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

推荐答案

可以使用多个字符串文字,但是它们必须具有相同的 type .您在第二行缺少b前缀:

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

仅当使用相同类型的字符串文字时,python解析器才会将它们合并为一个更长的bytes字符串对象.

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

它在Python 2上有效,因为b前缀是no-op; b'..''..'产生相同类型的对象. b前缀仅存在于Python 2中,以便更轻松地在同一代码库(多语言)中为Python 2和3编写代码.

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

这篇关于字节字符串跨越多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆