编码方法python 3

问题描述 投票:-1回答:1

我正在将一个应用程序从Ruby转换为Python,在Ruby中,有一个force_encoding方法用于编码utf8字符串。现在,在Python中没有完全匹配force_encoding所以,我使用的是编码方法,但是因为Python 3方法返回的字节不是字符串,但我需要编码字符串。

例如:str1 =“abc”str2 = str1.encode(“ascii”)//返回字节

我需要字符串而不是字节,我可以像使用相同的方式使用解码方法吗...

str1 =“abc”str2 = str1.encode(“ascii”)。decode(“ascii”)

我很困惑,如果解码方法再次将字符串转换为utf8而我需要ascii字符串。

还有一件事在Ruby中有方法编码来检查编码类型......

Ruby:str1 =“abc”print(str1.encoding)//返回utf8

所以,我们可以确定字符串是utf8编码的字符串在Python中是否有类似的东西?

python-3.x encode
1个回答
0
投票

所以,我们可以确定字符串是utf8编码的字符串在Python中是否有类似的东西?

在Python 3中,所有字符串都是unicode编码的,因此无需检查任何内容。

UPD:但如果你在谈论字节,我的意思是确定字节串的编码,这可以通过以下方式实现:

import chardet

the_encoding = chardet.detect(...)['encoding']
© www.soinside.com 2019 - 2024. All rights reserved.