将字符串编码为ascii [英] Encoding a string to ascii

查看:119
本文介绍了将字符串编码为ascii的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长字符串要编码为ascii.我在做:

I have a long string that I want to encode to ascii. I'm doing:

s = s.encode('ascii', 'replace')

但是我得到了

'ascii' codec can't decode byte 0xc3 in position 2646: ordinal not in range(128)

(我也尝试过'ignore',但无济于事.)

(I've also tried 'ignore' but it doesn't help.)

我在做什么错了?

推荐答案

您的字符串已经已编码,并且已进行了某些编码.在将其编码为ascii之前,您必须先对其进行解码.

Your string is already encoded with some encoding. Before encoding it to ascii, you must decode it first.

Python是 implicity 试图对其进行解码的(这就是为什么您得到UnicodeDecodeError而不是UnicodeEncodeError的原因).

Python is implicity trying to decode it (That's why you get a UnicodeDecodeError not UnicodeEncodeError).

您可以通过在尝试将其重新编码为ascii之前明确解码您的字节串(使用适当的编码)来解决该问题.

You can solve the problem by explicity decoding your bytestring (using the appropriate encoding) before trying to reencode it to ascii.

示例:

s = s.decode('some_encoding').encode('ascii', 'replace')

使用正确的编码,而不是'some_encoding'来编码您的字符串.

Use the correct encoding your string was encoded in first place, instead of 'some_encoding'.

在对字符串进行解码之前,您必须知道它使用的是哪种编码.你从哪里得到的字符串?

You have to know which encoding a string is using before you can decode it. Where did you get the string from?

这篇关于将字符串编码为ascii的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆