【发布时间】:2019-05-01 14:40:31
【问题描述】:
我正在将应用程序从 Ruby 转换为 Python,在 Ruby 中,有一个 force_encoding 方法用于对 utf8 字符串进行编码。现在,在 Python 中,force_encoding 没有完全匹配,因此,我使用的是 encode 方法,但由于 Python 3 方法返回的字节不是字符串,但我需要编码的字符串。
例如: str1 = "abc" str2 = str1.encode("ascii") // 返回字节数
我需要字符串而不是字节,我可以像...一样使用解码方法吗?
str1 = "abc" str2 = str1.encode("ascii").decode("ascii")
我很困惑,如果解码方法将字符串再次转换为 utf8 而我需要 ascii 字符串。
在 Ruby 中还有一件事是方法编码来检查编码类型...
红宝石: str1 = "abc" print (str1.encoding) // 返回 utf8
那么,我们可以确定字符串是utf8编码的字符串,Python中是否也有类似的东西???
【问题讨论】:
标签: python-3.x encode