Skip to content

python unicode string转码

Shuang0420 edited this page Jul 27, 2016 · 1 revision

unicode-string

s = '中文'
s = u'中文'.encode('utf-8')

>>> type('中文')

string-unicode

s = u'中文'
s = '中文'.decode('utf-8')
s = unicode('中文', 'utf-8')

>>> type(u'中文')

判断 unicode or string

>>> isinstance(u'中文', unicode)
True
>>> isinstance('中文', unicode)
False

>>> isinstance('中文', str)
True
>>> isinstance(u'中文', str)
False

简单原则:不要对str使用encode,不要对unicode使用decode (事实上可以对str进行encode的,具体见最后,为了保证简单,不建议)

[[TOC]]

Clone this wiki locally