📄 chap2.txt
字号:
For Python 1.6+, use of a string object method is
stylistically preferred in many cases:
>>> 'mary\011had a little lamb'.expandtabs(25)
'mary had a little lamb'
string.find(s, sub [,start [,end]])
"".find(sub [,start [,end]])
Return the index position of the first occurrence of 'sub'
in 's'. If the optional third or fourth arguments are
specified, only the corresponding slice of 's' is examined
(but result is position in s as a whole). Return -1 if
no occurrence is found. Position is zero-based, as with
Python list indexing:
>>> import string
>>> string.find("mary had a little lamb", "a")
1
>>> string.find("mary had a little lamb", "a", 3, 10)
6
>>> string.find("mary had a little lamb", "b")
21
>>> string.find("mary had a little lamb", "b", 3, 10)
-1
For Python 1.6+, use of a string object method is
stylistically preferred in many cases:
>>> 'mary had a little lamb'.find("ad")
6
SEE ALSO, `string.index()`, `string.rfind()`
string.index(s, sub [,start [,end]])
"".index(sub [,start [,end]])
Return the same value as does `string.find()` with same
arguments, except raise 'ValueError' instead of returning
-1 when sub does not occur in s.
>>> import string
>>> string.index("mary had a little lamb", "b")
21
>>> string.index("mary had a little lamb", "b", 3, 10)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "d:/py20sl/lib/string.py", line 139, in index
return s.index(*args)
ValueError: substring not found in string.index
For Python 1.6+, use of a string object method is
stylistically preferred in many cases:
>>> 'mary had a little lamb'.index("ad")
6
SEE ALSO, `string.find()`, `string.rindex()`
Several string methods that return Boolean values indicating
whether a string has a certain property. None of the '.is*()'
methods, however, have equivalents in the [string] module:
"".isalpha()
Return a true value if all the characters are alphabetic.
"".isalnum()
Return a true value if all the characters are alphanumeric.
"".isdigit()
Return a true value if all the characters are digits.
"".islower()
Return a true value if all the characters are lowercase
and there is at least one cased character:
>>> "ab123".islower(), '123'.islower(), 'Ab123'.islower()
(1, 0, 0)
SEE ALSO, `"".lower()`
"".isspace()
Return a true value if all the characters are whitespace.
"".istitle()
Return a true value if all the string has title casing
(each word capitalized).
SEE ALSO, `"".title()`
"".isupper()
Return a true value if all the characters are uppercase
and there is at least one cased character.
SEE ALSO, `"".upper()`
string.join(words=... [,sep=" "])
"".join(words)
Return a string that results from concatenating the
elements of the list 'words' together, with 'sep' between
each. The function `string.join()` differs from all
other [string] module functions in that it takes a list
(of strings) as a primary argument, rather than a string.
It is worth noting `string.join()` and `string.split()`
are inverse functions if 'sep' is specified to both; in
other words, 'string.join(string.split(s,sep),sep)==s'
for all 's' and 'sep'.
Typically, `string.join()` is used in contexts where it
is natural to generate lists of strings. For example,
here is a small program to output the list of
all-capital words from STDIN to STDOUT, one per line:
#---------- list_capwords.py ----------#
import string,sys
capwords = []
#*--- fix linebreak ---#
for line in sys.stdin.readlines():
for word in line.split():
if word == word.upper() and word.isalpha():
capwords.append(word)
print string.join(capwords, '\n')
The technique in the sample 'list_capwords.py' script can
be considerably more efficient than building up a string
by direct concatenation. However, Python 2.0's augmented
assignment reduces the performance difference:
>>> import string
>>> s = "Mary had a little lamb"
>>> t = "its fleece was white as snow"
>>> s = s +" "+ t # relatively "expensive" for big strings
>>> s += " " + t # "cheaper" than Python 1.x style
>>> lst = [s]
>>> lst.append(t) # "cheapest" way of building long string
>>> s = string.join(lst)
For Python 1.6+, use of a string object method is
stylistically preferred in some cases. However, just as
`string.join()` is special in taking a list as a first
argument, the string object method `"".join()` is unusual
in being an operation on the (optional) 'sep' string, not
on the (required) 'words' list (this surprises many new
Python programmers).
SEE ALSO, `string.split()`
string.joinfields(...)
Identical to `string.join()`.
string.ljust(s=..., width=...)
"".ljust(width)
Return a string with 's' padded with trailing spaces (but
not truncated) to occupy length 'width' (or more).
>>> import string
>>> string.ljust(width=30,s="Mary had a little lamb")
'Mary had a little lamb '
>>> string.ljust("Mary had a little lamb", 5)
'Mary had a little lamb'
For Python 1.6+, use of a string object method is
stylistically preferred in many cases:
>>> "Mary had a little lamb".ljust(25)
'Mary had a little lamb '
SEE ALSO, `string.rjust()`, `string.center()`
string.lower(s=...)
"".lower()
Return a string with any uppercase letters converted to
lowercase.
>>> import string
>>> string.lower("mary HAD a little lamb!")
'mary had a little lamb!'
>>> string.lower("Mary had a Little Lamb!")
'mary had a little lamb!'
For Python 1.6+, use of a string object method is
stylistically preferred in many cases:
>>> "Mary had a Little Lamb!".lower()
'mary had a little lamb!'
SEE ALSO, `string.upper()`
string.lstrip(s=...)
"".lstrip([chars=string.whitespace])
Return a string with leading whitespace characters
removed. For Python 1.6+, use of a string object method
is stylistically preferred in many cases:
>>> import string
>>> s = """
... Mary had a little lamb \011"""
>>> string.lstrip(s)
'Mary had a little lamb \011'
>>> s.lstrip()
'Mary had a little lamb \011'
Python 2.3+ accepts the optional argument 'chars' to the
string object method. All characters in the string
'chars' will be removed.
SEE ALSO, `string.rstrip(), `string.strip()`
string.maketrans(from, to)
Return a translation table string, for use with
`string.translate()`. The strings 'from' and 'to' must
be the same length. A translation table is a string of
256 successive byte values, where each position defines a
translation from the `chr()` value of the index to the
character contained at that index position.
>>> import string
>>> ord('A')
65
>>> ord('z')
122
>>> string.maketrans('ABC','abc')[65:123]
'abcDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz'
>>> string.maketrans('ABCxyz','abcXYZ')[65:123]
'abcDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwXYZ'
SEE ALSO, `string.translate()`
string.replace(s=..., old=..., new=... [,maxsplit=...])
"".replace(old, new [,maxsplit])
Return a string based on 's' with occurrences of 'old'
replaced by 'new'. If the fourth argument 'maxsplit' is
specified, only replace 'maxsplit' initial occurrences.
>>> import string
>>> string.replace("Mary had a little lamb", "a little", "some")
'Mary had some lamb'
For Python 1.6+, use of a string object method is
stylistically preferred in many cases:
>>> "Mary had a little lamb".replace("a little", "some")
'Mary had some lamb'
A common "trick" involving `string.replace()` is to use
it multiple times to achieve a goal. Obviously, simply
to replace several different substrings in a string,
multiple `string.replace()` operations are almost
inevitable. But there is another class of cases where
`string.replace()` can be used to create an intermediate
string with "placeholders" for an original substring in
a particular context. The same goal can always be
achieved with regular expressions, but sometimes staged
`string.replace()` operations are both faster and easier
to program:
>>> import string
>>> line = 'variable = val # see comments #3 and #4'
>>> # we'd like '#3' and '#4' spelled out within comment
>>> string.replace(line,'#','number ') # doesn't work
'variable = val number see comments number 3 and number 4'
>>> place_holder=string.replace(line,' # ',' !!! ') # insrt plcholder
>>> place_holder
'variable = val !!! see comments #3 and #4'
>>> place_holder=place_holder.replace('#','number ') # almost there
>>> place_holder
'variable = val !!! see comments number 3 and number 4'
>>> line = string.replace(place_holder,'!!!','#') # restore orig
>>> line
'variable = val # see comments number 3 and number 4'
Obviously, for jobs like this, a place holder must be
chosen so as not ever to occur within the strings
undergoing "staged transformation"; but that should be
possible generally since place holders may be as long as
needed.
SEE ALSO, `string.translate()`, `mx.TextTools.replace()`
string.rfind(s, sub [,start [,end]])
"".rfind(sub [,start [,end]])
Return the index position of the last occurrence of 'sub'
in 's'. If the optional third or fourth arguments are
specified only the corresponding slice of 's' is examined
(but result is position in 's' as a whole). Return -1 if
no occurrence is found. Position is zero-based, as with
Python list indexing:
>>> import string
>>> string.rfind("mary had a little lamb", "a")
19
>>> string.rfind("mary had a little lamb", "a", 3, 10)
9
>>> string.rfind("mary had a little lamb", "b")
21
>>> string.rfind("mary had a little lamb", "b", 3, 10)
-1
For Python 1.6+, use of a string object method
stylistically preferred in many cases:
>>> 'mary had a little lamb'.rfind("ad")
6
SEE ALSO, `string.rindex()`, `string.find()`
string.rindex(s, sub [,start [,end]])
"".rindex(sub [,start [
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -