Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python3编码方法_Python 3.x_Encode - Fatal编程技术网

Python 3.x Python3编码方法

Python 3.x Python3编码方法,python-3.x,encode,Python 3.x,Encode,我正在将一个应用程序从Ruby转换为Python,在Ruby中,有一个force_编码方法用于对utf8字符串进行编码。现在,在Python中,force_编码没有精确匹配,因此,我使用encode方法,但在中,因为Python 3方法返回的字节不是字符串,但我需要编码字符串 例如: str1=“abc” str2=str1.encode(“ascii”)//返回字节 我需要字符串而不是字节,我可以用同样的方式像解码方法 str1=“abc” str2=str1.编码(“ascii”).解码(“

我正在将一个应用程序从Ruby转换为Python,在Ruby中,有一个force_编码方法用于对utf8字符串进行编码。现在,在Python中,force_编码没有精确匹配,因此,我使用encode方法,但在中,因为Python 3方法返回的字节不是字符串,但我需要编码字符串

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

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

str1=“abc” str2=str1.编码(“ascii”).解码(“ascii”)

如果decode方法再次将字符串转换为utf8,我会感到困惑,因为我需要ascii字符串

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

红宝石: str1=“abc” print(str1.encoding)//返回utf8

因此,我们可以确定字符串是utf8编码的字符串,Python中是否也有类似的内容

因此,我们可以确定字符串是utf8编码的字符串,Python中是否也有类似的内容

在Python3中,所有字符串都是unicode编码的,因此无需进行任何检查

UPD:但如果你说的是字节,我的意思是确定字节字符串的编码,这可以通过如下方式完成:

import chardet

the_encoding = chardet.detect(...)['encoding']