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

(yzsuai) #1
True
>>> 'Ni' in mystr # when not found
False
>>> mystr.find('Ni')
-1

>>> mystr = '\t Ni\n'
>>> mystr.strip() # remove whitespace
'Ni'
>>> mystr.rstrip() # same, but just on right side
'\t Ni'

String methods also provide functions that are useful for things such as case conver-
sions, and a standard library module named string defines some useful preset variables,
among other things:


>>> mystr = 'SHRUBBERY'
>>> mystr.lower() # case converters
'shrubbery'

>>> mystr.isalpha() # content tests
True
>>> mystr.isdigit()
False

>>> import string # case presets: for 'in', etc.
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

>>> string.whitespace # whitespace characters
' \t\n\r\x0b\x0c'

There are also methods for splitting up strings around a substring delimiter and putting
them back together with a substring in between. We’ll explore these tools later in this
book, but as an introduction, here they are at work:


>>> mystr = 'aaa,bbb,ccc'
>>> mystr.split(',') # split into substrings list
['aaa', 'bbb', 'ccc']

>>> mystr = 'a b\nc\nd'
>>> mystr.split() # default delimiter: whitespace
['a', 'b', 'c', 'd']

>>> delim = 'NI'
>>> delim.join(['aaa', 'bbb', 'ccc']) # join substrings list
'aaaNIbbbNIccc'

>>> ' '.join(['A', 'dead', 'parrot']) # add a space between
'A dead parrot'

System Scripting Overview | 81
Free download pdf