15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

method (see example below). There is really no longer a need to import the string module unless you<br />

are trying to access some of the older string constants which that module defines.<br />

Note: Although easier to learn for beginners, we recommend not using string concatenation when<br />

performance counts. The reason is that for every string that is part of a concatenation, <strong>Python</strong> has to<br />

allocate new memory for all strings involved, including the result. Instead, we recommend you either<br />

use the string format operator ( % ), as in the examples below, or put all of the substrings in a list, and<br />

using one join() call to put them all together:<br />

>>> '%s %s' % ('Spanish', 'Inquisition')<br />

'Spanish Inquisition'<br />

>>><br />

>>> s = ' '.join(('Spanish', 'Inquisition', 'Made Easy'))<br />

>>> s<br />

'Spanish Inquisition Made Easy'<br />

>>><br />

>>> # no need to import string to use string.upper():<br />

>>> ('%s%s' % (s[:3], s[20])).upper()<br />

'SPAM'<br />

Compile-Time String Concatenation<br />

The above syntax using the addition operator performs the string concatenation at runtime, and its use<br />

is the norm. There is a less frequently used syntax that is more of a programmer convenience feature.<br />

<strong>Python</strong>'s syntax allows you to create a single string from multiple string literals placed adjacent to each<br />

other in the body of your source code:<br />

>>> foo = "Hello" 'world!'<br />

>>> foo<br />

'Helloworld!'<br />

It is a convenient way to split up long strings without unnecessary backslash escapes. As you can see<br />

from the above, you can mix quotation types on the same line. Another good thing about this feature is<br />

that you can add comments too, like this example:<br />

>>> f = urllib.urlopen('http://' # protocol<br />

... 'localhost' # hostname<br />

... ':8000' # port<br />

... '/cgi-bin/friends2.py') # file<br />

As you can imagine, here is what urlopen() really gets as input:<br />

>>> 'http://' 'localhost' ':8000' '/cgi-bin/friends2.py'<br />

'http://localhost:8000/cgi-bin/friends2.py'<br />

Regular String Coercion to Unicode<br />

When concatenating regular and Unicode strings, regular strings are converted to Unicode first before<br />

the operation occurs:

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

Saved successfully!

Ooh no, something went wrong!