评估顺序、unicode 字符串和格式

Order of evaluation , unicode string & format

这里有很多unicode映射的字符串。

unicode_strings = ["\U00000{:0>3}".format(str.upper(hex(i))[2:]) for i in range(16)]

但是此代码会发出错误消息。

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-6: truncated \UXXXXXXXX escape

这是因为评估的顺序。

首先,计算“\U00000”,其次,执行format

如错误信息,unicode字符必须是"\UXXXXXXXX"的块。

第一次评估 Unicode 字符,但这不是当时合适的块。

执行format函数时,必须完整构造unicode字符。

我知道 cap 字符串 'r' 可以转义此错误消息,但它不会生成 unicode 字符串。

如何第一次给字符串附加“\U”或执行格式化功能?

如果我删除'\U',结果就是乌托邦。

 ['00000001',
 '00000002',
 '00000003',
 '00000004',
 '00000005',
 '00000006',
 '00000007',
 '00000008',
 '00000009',
 '0000000A',
 '0000000B',
 '0000000C',
 '0000000D',
 '0000000E',
 '0000000F']

更新: 我想要这样的结果。

['\U00000001',
 '\U00000002',
 '\U00000003',
 '\U00000004',
 '\U00000005',
 '\U00000006',
 '\U00000007',
 '\U00000008',
 '\U00000009',
 '\U0000000A',
 '\U0000000B',
 '\U0000000C',
 '\U0000000D',
 '\U0000000E',
 '\U0000000F']

我想获取 Unicode 映射中的字符序列。

不完全确定你到底在追求什么,但考虑到例如 \U00000000\x00 相同并生成此列表,无论如何以下理解似乎更有意义:

unicode_strings = [chr(i) for i in range(16)]

如果问题是为什么会发生这种情况,format 文档可能有点微妙:*)

The string on which this method is called can contain literal text or replacement fields delimited by braces {}... Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

但基本上,文字字符串和 "replacement fields" 已被识别,并且每个都被认为是这样。在您的情况下,字符串文字 \U00000 正在被考虑并且无效,因为在 \U 之后预期有四个字节的十六进制值。或者换句话说,这不是真正的顺序问题(先是字面量,然后是表达式),而是 str 如何分成块/处理(首先识别文字和表达式并按此处理)。

因此,如果您想为更大的字符串生成做类似的事情,您可以按如下方式进行:

somelist = [f"abcd{chr(i)}efgh" for i in range(16)]

*) PEP-498 在 f-strings 上可能更明确一点(并且在这方面的机制是相同的),即:

f-strings are parsed in to literal strings and expressions...

The parts of the f-string outside of braces are literal strings. These literal portions are then decoded. For non-raw f-strings, this includes converting backslash escapes such as '\n', '\"', "\'", '\xhh', '\uxxxx', '\Uxxxxxxxx', and named unicode characters '\N{name}' into their associated Unicode characters.