12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

garbage collects (reclaims the space of) old unused string objects as you go, so newerobjects reuse the space held by prior values. <strong>Python</strong> is usually more efficient than youmight expect.Finally, it’s also possible to build up new text values with string formatting expressions:>>> 'That is %d %s bird!' % (1, 'dead') # Like C sprintfThat is 1 dead bird!This turns out to be a powerful operation. The next section shows how it works.String Formatting<strong>Python</strong> defines the % binary operator to work on strings (you may recall that this isalso the remainder of division, or modulus, operator for numbers). When applied tostrings, this operator serves the same role as C’s sprintf function; the % provides asimple way to format values as strings, according to a format definition string. Inshort, the % operator provides a compact way to code multiple string substitutions.To format strings:1. On the left of the % operator, provide a format string containing one or moreembedded conversion targets, each of which starts with a % (e.g., %d).2. On the right of the % operator, provide the object (or objects, in parentheses)that you want <strong>Python</strong> to insert into the format string on the left in place of theconversion target (or targets).For instance, in the last example, we looked at in the prior section, the integer 1replaces the %d in the format string on the left, and the string 'dead' replaces the %s.The result is a new string that reflects these two substitutions.Technically speaking, string formatting expressions are usually optional—you cangenerally do similar work with multiple concatenations and conversions. However,formatting allows us to combine many steps into a single operation. It’s powerfulenough to warrant a few more examples:>>> exclamation = "Ni">>> "The knights who say %s!" % exclamation'The knights who say Ni!'>>> "%d %s %d you" % (1, 'spam', 4)'1 spam 4 you'>>> "%s -- %s -- %s" % (42, 3.14159, [1, 2, 3])'42 -- 3.14159 -- [1, 2, 3]'The first example here plugs the string "Ni" into the target on the left, replacing the%s marker. In the second example, three values are inserted into the target string.Note that when you’re inserting more than one value, you need to group the valueson the right in parentheses (i.e., put them in a tuple).140 | Chapter 7: Strings

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

Saved successfully!

Ooh no, something went wrong!