【问题标题】:How to convert UTF-8 notation to python unicode notation如何将 UTF-8 表示法转换为 python unicode 表示法
【发布时间】:2022-01-16 03:12:43
【问题描述】:

使用 python3.8 我想将 unicode 表示法转换为 python 表示法:

s = 'U+00A0'
result = s.lower() # output  'u+00a0'

我想用\u替换u+

result = s.lower().replace('u+','\u') 

但我得到了错误:

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

如何将符号U+00A0 转换为\u00a0

编辑:

之所以想得到\u00a0,是为了进一步使用encode的方法得到b'\xc2\xa0'

我的问题:给定以下符号 U+00A0 的字符串,我想将其转换为字节码 b'\xc2\xa0'

【问题讨论】:

  • @tdelaney:我想得到文字字符串\u00a0
  • @tdelaney 我想将文字 U+00A0 转换为文字字符串 \u00a0
  • @tdelaney:我的目标是将字符串 'U+00A0' 转换为 b'\xc2\xa0'
  • @Mark:让我更新一下这个问题,让它更清楚。我看到我的问题是 XY 问题。
  • 为什么不\xa0

标签: python unicode character-encoding


【解决方案1】:

你正在为某物的表现与它的价值而苦苦挣扎……

import re
re.sub("u\+([0-9a-f]{4})",lambda m:chr(int(m.group(1),16)),s)

但是对于 u+00a0 这变成 \xa0

但与文字 \u00a0

相同
s = "\u00a0"
print(repr(s))

一旦你将正确的值作为 unicode 字符串,你就可以将它编码为 utf8

s = "\xa0"
print(s.encode('utf8'))
# b'\xc2\xa0'

所以这里只是最终答案

import re
s = "u+00a0"
s2 = re.sub("u\+([0-9a-f]{4})",lambda m:chr(int(m.group(1),16)),s)
s_bytes = s2.encode('utf8') # b'\xc2\xa0'

【讨论】:

  • 我已经更新了我的问题以明确说明。
  • @OK-Validation 我也更新了我的答案...
  • 我不明白你的回答。您假设输入为\u00a0,这是我的问题首先如何获得它。
  • 我回答的第一行就是这样做的......
  • 请明确添加import re,以免初学者感到困惑
【解决方案2】:

你也可以这样用:

>>> s = 'U+00A0'
>>> s = s.replace('U+', '\\u').encode().decode('unicode_escape').encode()
>>> s
b'\xc2\xa0'

【讨论】:

  • @OK-Validation 更新
  • 有效!感谢更新
【解决方案3】:

您需要使用第二个\ 转义replace 中的\

result = s.lower().replace('u+','\\u') 
print(result)

会给你\u00a0

【讨论】:

  • 否;它返回\\u00a0 而不是\u00a0
  • 不在我的终端中......
猜你喜欢
  • 2016-07-08
  • 1970-01-01
  • 2015-05-30
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-07
  • 2015-11-14
相关资源
最近更新 更多