【问题标题】:Using f-strings with unicode escapes使用带有 unicode 转义的 f 字符串
【发布时间】:2021-11-21 15:03:03
【问题描述】:

我的字符串看起来像这样: a = "testing test<U+00FA>ing <U+00F3>"

格式并不总是这样,但括号中的那些 unicode 字符会分散在整个代码中。我想将它们转换为它们所代表的实际 unicode 字符。我试过这个功能:

def replace_unicode(s):
    uni = re.findall(r'<U\+\w\w\w\w>', s)

    for a in uni:
        s = s.replace(a, f'\u{a[3:7]}')
    return s

这成功地找到了所有的 unicode 字符串,但它不允许我将它们放在一起以这种方式创建一个 unicode 转义。

  File "D:/Programming/tests/test.py", line 8
    s = s.replace(a, f'\u{a[3:7]}')
                     ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape

如何使用 f 字符串或通过其他方法以及从字符串中获取的信息创建 unicode 转义字符?

【问题讨论】:

    标签: python python-3.x unicode


    【解决方案1】:

    chepner's answer 很好,但您实际上并不需要 f 字符串。 int(a[3:7], base=16) 工作得很好。

    此外,使用re.sub() 而不是re.findall() 然后str.replace() 会更有意义。我还将正则表达式限制为仅十六进制数字并将它们分组。

    import re
    
    def replace_unicode(s):
        pattern = re.compile(r'<U\+([0-9A-F]{4})>')
        return pattern.sub(lambda match: chr(int(match.group(1), base=16)), s)
    
    a = "testing test<U+00FA>ing <U+00F3>"
    print(replace_unicode(a))  # -> testing testúing ó
    

    【讨论】:

      【解决方案2】:

      您可以使用 f 字符串为 int 创建一个适当的参数,chr 函数可以使用其结果来生成所需的字符。

      for a in uni:
          s = s.replace(a, chr(int(f'0x{a[3:7]}', base=16)))
      

      【讨论】:

      • 效果很好,谢谢!
      • 当然你不需要0x,因为你指定了基数,因此你根本不需要 f 字符串。
      猜你喜欢
      • 2015-10-16
      • 2023-03-31
      • 1970-01-01
      • 2020-02-28
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      相关资源
      最近更新 更多