【问题标题】:Convert a string to a byte string将字符串转换为字节字符串
【发布时间】:2019-07-16 04:26:20
【问题描述】:

我想将字符串转换为字节字符串。字符串正是以这种形式出现的。 'сp1251' 编码。怎么做才对?

str = 'см³' 
bytes(str, 'cp1251')

结果,我得到了

UnicodeEncodeError:“charmap”编解码器无法对字符“\xb3”进行编码 位置 2:字符映射到

【问题讨论】:

  • 我无法以这种形式重写字符串 см ^ 3. 与上标一致。
  • 查看代码页 1251 en.wikipedia.org/wiki/Windows-1251,没有字符 ³。你想怎么编码?
  • 您可以使用'utf-8'编码进行转换。
  • arsho,感谢您的回复。当您使用 utf-8 写入文件时,结果是 'РјВі'
  • Andrej Kesely,感谢您的回复。那不告诉我应该用什么编码?

标签: python-3.x


【解决方案1】:

您可以在文本模式下编写字符串s,Unicode 字符串处理已经在 Python3 中标准化并且是自动完成的(从内存(变量 s)到文件自动执行 32 位 Unicode 到 utf-8 的转换:

s = 'см³'

# with text-mode:

with open('file.txt', 'w') as f_out:
    f_out.write(s)

print(open('file.txt', 'r').read())

打印:

см³

如果你想具体一点,你可以使用二进制模式读取/写入文件b标志:

# with binary-mode:

with open('file.txt', 'wb') as f_out:
    f_out.write(s.encode('utf-8'))

print(open('file.txt', 'rb').read().decode('utf-8'))

打印:

см³

【讨论】:

    猜你喜欢
    • 2019-10-10
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多