Professional Python by Sneeringer Luke

Professional Python by Sneeringer Luke

Author:Sneeringer, Luke [Sneeringer, Luke]
Language: eng
Format: azw3, epub
ISBN: 9781119070788
Publisher: Wiley
Published: 2015-10-06T16:00:00+00:00


Python 2 Strings

Python 2 strings mostly work similarly, but with some subtle but very important distinctions.

The first distinction is the name of the classes. The Python 3 str class is called unicode in Python 2. In and of itself, this is fine. However, the Python 3 bytes class is called str in Python 2. This means that a Python 3 str is a text string, whereas a Python 2 str is a byte string. If you are using Python 2, it is critically important to understand this distinction.

Instantiating a string with no prefix gives you a str (remember, this is a byte string!) instance.

>>> byte_str = 'The quick brown fox jumped over the lazy dogs.' >>> type(byte_str) <type 'str'>

If you want a text string in Python 2, you prefix the string literal with the u character, as shown here:

>>> text_str = u'The quick brown fox jumped over the lazy dogs.' >>> type(text_str) <type 'unicode'>

Unlike Python 3, Python 2 does attempt to implicitly convert between text strings and byte strings. The way that this works is that if the interpreter encounters a mixed operation, it will first convert the byte string to a text string, and then perform the operation against the text strings.

It works this way so that an operation against a byte string and a text string will return a text string:

>>> 'foo' + u'bar' u'foobar'

The interpreter performs this implicit decoding using whatever the default encoding is. On Python 2, this is almost always ASCII. Python defines a method, sys.getdefaultencoding, which provides the default codec for implicitly converting between text strings and byte strings.

>>> import sys >>> sys.getdefaultencoding() 'ascii'

This means that many of the previous Python 3 examples show distinctly different behavior in Python 2.

>>> 'foo' == u'foo' True >>> >>> d = {u'foo': u'bar'} >>> d['foo'] u'bar'



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.