python2字符串编码_Python 2.x中的字符串使用哪种编码?

What is the default encoding used for encoding strings in python 2.x? I've read that there are two possible ways to declare a string.

string = 'this is a string'

unicode_string = u'this is a unicode string'

The second string is in Unicode.

What is the encoding of the first string?

解决方案

As per Python default/implicit string encodings and conversions (reciting its Py2 part concisely, to minimize duplication):

There are actually multiple independent "default" string encodings in Python 2, used by different parts of its functionality.

Parsing the code and string literals:

str from a literal -- will contain raw bytes from the file, no transcoding is done

unicode from a literal -- the bytes from the file are decode'd with the file's "source encoding" which defaults to ascii

with unicode_literals future, all literals in the file are treated as Unicode literals

Transcoding/type conversion:

strunicode type conversion and encode/decode w/o arguments are done with sys.getdefaultencoding()

which is ascii almost always, so any national characters will cause a UnicodeError

str can only be decode'd and unicode -- encode'd. Trying otherwise will involve an implicit type conversion (with the aforementioned result)

I/O, including printing:

unicode -- encode'd with .encoding if set, otherwise implicitly converted to str (with the aforementioned result)

str -- raw bytes are written to the stream, no transcoding is done. For national characters, a terminal will show different glyphs depending on its locale settings.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值