[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
Moreover, in Python today all normal string methods apply to both bytes and str
strings. The latter makes them applicable to arbitrarily encoded Unicode text, simply
because the str type is Unicode text, even if it’s only ASCII. These methods originally
appeared as function in the string module, but are only object methods today; the
string module is still present because it contains predefined constants (e.g.,
string.ascii_uppercase), as well as the Template substitution interface in 2.4 and
later—one of the techniques discussed in the next section.

Templating with Replacements and Formats


By way of review, let’s take a quick look at string methods in the context of some of
their most common use cases. As we saw when generating HTML forwarding pages in
Chapter 6, the string replace method is often adequate by itself as a string templating
tool—we can compute values and insert them at fixed positions in a string with simple
replacement calls:
>>> template = '---$target1---$target2---'
>>> val1 = 'Spam'
>>> val2 = 'shrubbery'
>>> template = template.replace('$target1', val1)
>>> template = template.replace('$target2', val2)
>>> template
'---Spam---shrubbery---'
As we also saw when generating HTML reply pages in the CGI scripts of Chapters 15
and 16, the string % formatting operator is also a powerful templating tool, especially
when combined with dictionaries—simply fill out a dictionary with values and apply
multiple substitutions to the HTML string all at once:
>>> template = """
... ---
... ---%(key1)s---
... ---%(key2)s---
... """
>>>
>>> vals = {}
>>> vals['key1'] = 'Spam'
>>> vals['key2'] = 'shrubbery'
>>> print(template % vals)

---
---Spam---
---shrubbery---
Beginning with Python 2.4, the string module’s Template feature is essentially a sim-
plified and limited variation of the dictionary-based format scheme just shown, but it
allows some additional call patterns which some may consider simpler:
>>> vals
{'key2': 'shrubbery', 'key1': 'Spam'}

1408 | Chapter 19: Text and Language

Do


wnload from Wow! eBook <www.wowebook.com>

Free download pdf