【问题标题】:How to transform a string into a Unicode character如何将字符串转换为 Unicode 字符
【发布时间】:2020-11-30 18:14:53
【问题描述】:

我想创建一个非常简单的代码来获取多个字符串输入并显示为 Unicode 字符,例如:

2119 01b4 2602 210c 00f8 1f24 (这应该显示带有一些符号的“Python”)

但我不断收到以下异常:

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

我正在尝试使用 '\u' 来保持简单,但如果没有其他方法可以做到这一点,我不会打扰。

我的代码:

while True:
    string = input()
    print(f'\u{string}', end='')

我在 Swift 中搜索并发现了一些东西,这正是我想在 Python 中做的,但我不太明白:Print unicode character from variable (swift)

【问题讨论】:

  • 查看ord()函数。
  • '\u0000' 是 Python 文字语法的一部分。您不能使用替换来创建语法,就像您可以运行 value = ''' ' + str(something) + ' ''',然后期望 f'{value}' 调用 str(something) 一样;如果它确实有效,则意味着存在严重的安全漏洞。

标签: python unicode


【解决方案1】:

假设您真的不关心是否使用\u 语法,这看起来像:

while True:
    string = input()
    print(chr(int(string, 16)), end='')

如果您出于某种原因确实在乎:

while True:
    string = input()
    print((br'\u' + string.encode('utf-8')).decode('unicode_escape'), end='')

【讨论】:

    【解决方案2】:

    问题在于 unicode 转义优先于 f-string 格式规范。它将 "\u{str" 视为 4 个字符的转义序列。您可以将其分为两个步骤:创建转义然后解码。由于 unicode 字符可以超过 4 个字节,所以你也可以变大。

    >>> import codecs
    >>> string = "2119 01b4 2602 210c 00f8 1f24"
    >>> for s in string.split(" "):
    ...     print(codecs.decode(rf"\U{s.zfill(8)}", "unicode-escape"), end="")
    ... 
    ℙƴ☂ℌøἤ 
    

    【讨论】:

      【解决方案3】:

      您不能直接构造\uxxxx 转义序列,因为这是一种语言构造,但使用chr 将Unicode 序数转换为字符更直接。 int(s,16) 还会将十六进制字符串转换为整数:

      >>> print(''.join(chr(int(x,16)) for x in input().split()))
      2119 01b4 2602 210c 00f8 1f24
      ℙƴ☂ℌøἤ
      

      【讨论】:

        猜你喜欢
        • 2011-10-27
        • 1970-01-01
        • 2017-03-04
        • 1970-01-01
        • 1970-01-01
        • 2017-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多