15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

6.2. Strings<br />

Strings are among the most popular types in <strong>Python</strong>. We can create them simply by enclosing<br />

characters in quotes. <strong>Python</strong> treats single quotes the same as double quotes. This contrasts with most<br />

other shell-type scripting languages, which use single quotes for literal strings and double quotes to<br />

allow escaping of characters. <strong>Python</strong> uses the "raw string" operator to create literal quotes, so no<br />

differentiation is necessary. Other languages such as C use single quotes for characters and double<br />

quotes for strings. <strong>Python</strong> does not have a character type; this is probably another reason why single<br />

and double quotes are treated the same.<br />

Nearly every <strong>Python</strong> application uses strings in one form or another. Strings are a literal or scalar type,<br />

meaning they are treated by the interpreter as a singular value and are not containers that hold other<br />

<strong>Python</strong> objects. Strings are immutable, meaning that changing an element of a string requires creating a<br />

new string. Strings are made up of individual characters, and such elements of strings may be accessed<br />

sequentially via slicing.<br />

With the unification of types and classes in 2.2, there are now actually three types of strings in <strong>Python</strong>.<br />

Both regular string (str) and Unicode string (unicode) types are actually subclassed from an abstract<br />

class called basestring. This class cannot be instantiated, and if you try to use the factory function to<br />

make one, you get this:<br />

>>> basestring('foo')<br />

Traceback (most recent call last):<br />

File "", line 1, in <br />

TypeError: The basestring type cannot be instantiated<br />

How to Create and Assign Strings<br />

Creating strings is as simple as using a scalar value or having the str() factory function make one and<br />

assigning it to a variable:<br />

>>> aString = 'Hello World!' # using single quotes<br />

>>> anotherString = "<strong>Python</strong> is cool!" # double quotes<br />

>>> print aString # print, no quotes!<br />

Hello World!<br />

>>> anotherString # no print, quotes!<br />

'<strong>Python</strong> is cool!'<br />

>>> s = str(range(4)) # turn list to string<br />

>>> s<br />

'[0, 1, 2, 3]'<br />

How to Access Values (Characters and Substrings) in Strings<br />

<strong>Python</strong> does not support a character type; these are treated as strings of length one, thus also

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!