如何将 unicode 类型转换为 str 类型?(也许这不是编码或解码的问题)

how can i convert unicode type to str type?(maybe it isn't a matter of encode or decode)

我有一个字符串 s 定义为:

s='中文'

我需要将其编码为转义代码单元 (\u4e2d\u6587),如下所示:

s2='\u4e2d\u6587'

我试过这个:

s1=unicode(s,'cp936') 
print type(s1)

但它会打印 <type 'unicode'>(如果我打印 s,我会得到 <type 'str'>)。

如果重要的话我正在使用 Python 2.7.8.

s='中文' 是 Python 2 中的一个字节串,所以字节串的编码不明确。它将在源文件的编码中,但缺少该信息.

但是,要使用 Unicode 字符串进行转换很简单:

>>> s = u'中文'
>>> type(s)
<type 'unicode'>
>>> b = s.encode('unicode_escape')
>>> b
'\u4e2d\u6587'
>>> type(b)
<type 'str'>
>>> print b
\u4e2d\u6587