【问题标题】:Iterating over Unicode Characters遍历 Unicode 字符
【发布时间】:2023-02-21 23:55:44
【问题描述】:

我想像这样在 Python 中循环 Unicode-Characters:

hex_list = "012346789abcdef"
for _1 in hex_list:
    for _2 in hex_list:
        for _3 in hex_list:
            for _4 in hex_list:
                my_char = r"\u" + _1 + _2 + _3 + _4
                print(my_char)

正如预期的那样打印出来:

\u0000
\u0001
...
\uffff

然后我尝试更改上面的代码以不打印 Unicode 而是打印相应的字符:

hex_list = "012346789abcdef"
for _1 in hex_list:
    for _2 in hex_list:
        for _3 in hex_list:
            for _4 in hex_list:
                my_char = r"\u" + _1 + _2 + _3 + _4
                eval("print(my_char)")

但这输出与之前的代码相同。

hex_list = "012346789abcdef"
for _1 in hex_list:
    for _2 in hex_list:
        for _3 in hex_list:
            for _4 in hex_list:
                eval("print(" + r"\u" + f"{_1}{_2}{_3}{_4})")

这样的事情会引发以下错误消息:

eval("print(" + r"\u" + f"{_1}{_2}{_3}{_4})")
  File "<string>", line 1
    print(\u0000)
                ^
SyntaxError: unexpected character after line continuation character

是什么让这段代码按预期工作?

【问题讨论】:

  • 摆弄evaling 字符串文字闻起来像XY problem。为什么不用chr(codepoint)
  • @Brian 要清楚,codepoint 需要是一个整数,可以用int(f"{_1}{_2}{_3}{_4})", 16) 得到
  • Python 字符串是 Unicode。所有字符都是 Unicode 字符。 Unicode 不是某种转义序列,它是一种将字符映射到字节的方法。
  • 另外,请注意 eval("print(my_char)")print(my_char) 相同,它只是打印变量 my_char 的字符串内容
  • 鉴于事实Python 字符串是 Unicode,您可以使用 chr 将 Unicode 代码点转换为具有该字符的字符串,例如 print(chr(1081))。您可以从 0 迭代到您想要生成字符的任何数字

标签: python loops unicode backslash


【解决方案1】:

Python 字符串已经是 Unicode。 Unicode 不是某种转义序列,它是一种将字符映射到字节的方法。

鉴于此,您可以使用chr 将Unicode 代码点转换为具有该字符的字符串,例如print(chr(1081))。正如函数的文档所说:

返回表示其 Unicode 代码点为整数 i 的字符的字符串。例如,chr(97) 返回字符串 'a',而 chr(8364) 返回字符串 '€'。这是 ord() 的逆运算。

参数的有效范围是从 0 到 1,114,111

一个简单的循环就可以生成所有有效字符。实际上打印它们是另一回事:

for i in range(0, 1114110 ):
    print(chr(i))

在我的机器上运行它最终失败了

UnicodeEncodeError: 'utf-8' 编解码器无法对位置 0 中的字符 'ud800' 进行编码:不允许代理项

该值无法转换为可以在我的终端上打印的形式,它使用 UTF8

【讨论】:

  • 你遗漏了最后两个。顺便说一句,0x110000 更容易记住。
  • 我不同意。尝试例如print(chr(0xD800)) 然后你得到UnicodeEncodeError: 'utf-8' 编解码器无法对位置 0 中的字符 'ud800' 进行编码:不允许代理项立即地…
猜你喜欢
  • 2017-05-03
  • 1970-01-01
  • 2016-02-20
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 2014-01-14
  • 2018-05-15
  • 2020-03-28
相关资源
最近更新 更多