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

(yzsuai) #1

pass a number to the numlines argument (e.g., the last line in Example 2-1 passes 10 to
the numlines argument of the more function).


The splitlines string object method call that this script employs returns a list of sub-
strings split at line ends (e.g., ["line", "line",...]). An alternative splitlines method
does similar work, but retains an empty line at the end of the result if the last line is
\n terminated:


>>> line = 'aaa\nbbb\nccc\n'

>>> line.split('\n')
['aaa', 'bbb', 'ccc', '']

>>> line.splitlines()
['aaa', 'bbb', 'ccc']

As we’ll see more formally in Chapter 4, the end-of-line character is normally always
\n (which stands for a byte usually having a binary value of 10) within a Python script,
no matter what platform it is run upon. (If you don’t already know why this matters,
DOS \r characters in text are dropped by default when read.)


String Method Basics


Now, Example 2-1 is a simple Python program, but it already brings up three important
topics that merit quick detours here: it uses string methods, reads from a file, and is set
up to be run or imported. Python string methods are not a system-related tool per se,
but they see action in most Python programs. In fact, they are going to show up
throughout this chapter as well as those that follow, so here is a quick review of some
of the more useful tools in this set. String methods include calls for searching and
replacing:


>>> mystr = 'xxxSPAMxxx'
>>> mystr.find('SPAM') # return first offset
3
>>> mystr = 'xxaaxxaa'
>>> mystr.replace('aa', 'SPAM') # global replacement
'xxSPAMxxSPAM'

The find call returns the offset of the first occurrence of a substring, and replace does
global search and replacement. Like all string operations, replace returns a new string
instead of changing its subject in-place (recall that strings are immutable). With these
methods, substrings are just strings; in Chapter 19, we’ll also meet a module called
re that allows regular expression patterns to show up in searches and replacements.


In more recent Pythons, the in membership operator can often be used as an alternative
to find if all we need is a yes/no answer (it tests for a substring’s presence). There are
also a handful of methods for removing whitespace on the ends of strings—especially
useful for lines of text read from a file:


>>> mystr = 'xxxSPAMxxx'
>>> 'SPAM' in mystr # substring search/test

80 | Chapter 2: System Tools

Free download pdf