Py学习  »  问与答

请教:关于python中编码的问题

Lebesgue • 11 年前 • 4108 次点击  

python中有没有办法使得,我不用知道这个字符串是什么编码,我都可以把他转成另一种编码? 我在网上看到一个例子是下面这样的,不知道靠不靠谱?

def de_unicode(str):

if isinstance(str, unicode):

    return str

for type in ('utf-8', 'gbk', 'gb2312', 'big5', 'utf16', 'utf32'):

    try:

        return str.decode(type)

    except:

        pass

return str

还有一种方法是chardet来先判断出这个字符当前的编码类型,再解码,然后再编码。但是这个chardet也是不能保证100%正确的。返回有个可信度。

还有smart_unicode(), smart_str() 这两个函数是干嘛用的?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/310
文章 [ 1 ]  |  最新文章 11 年前
Py站长
Reply   •   1 楼
Py站长    11 年前

http://www.cnblogs.com/xiaowuyi/archive/2012/03/09/2387173.html

smart_text(s, encoding='utf-8', strings_only=False, errors='strict')
Returns a text object representing s – unicode on Python 2 and str on Python 3. Treats bytestrings using the encoding codec.

If strings_only is True, don’t convert (some) non-string-like objects.

https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield