代码改变世界

Python String模块详解

2017-05-15 09:34  linkxu  阅读(2884)  评论(0编辑  收藏  举报
 1 >>> import string
 2 
 3 >>> string.ascii_letters
 4 
 5 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
 6 
 7 >>> string.ascii_lowercase
 8 
 9 'abcdefghijklmnopqrstuvwxyz'
10 
11 >>> string.ascii_uppercase
12 
13 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
14 
15 >>> string.digits
16 
17 '0123456789'
18 
19 >>> string.hexdigits
20 
21 '0123456789abcdefABCDEF'
22 
23 >>> string.letters
24 
25 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
26 
27 >>> string.lowercase
28 
29 'abcdefghijklmnopqrstuvwxyz'
30 
31 >>> string.uppercase
32 
33 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
34 
35 >>> string.octdigits
36 
37 '01234567'
38 
39 >>> string.punctuation
40 
41 '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
42 
43 >>> string.printable
44 
45 '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
46 
47 >>> string.whitespace
48 
49 '\t\n\x0b\x0c\r

 

 

  1 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
  2 
  3 'a, b, c'
  4 
  5 >>> '{}, {}, {}'.format('a', 'b', 'c')  # 2.7+ only
  6 
  7 'a, b, c'
  8 
  9 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
 10 
 11 'c, b, a'
 12 
 13 >>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
 14 
 15 'c, b, a'
 16 
 17 >>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
 18 
 19 'abracadabra'
 20 
 21 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
 22 
 23 'Coordinates: 37.24N, -115.81W'
 24 
 25 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
 26 
 27 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
 28 
 29 'Coordinates: 37.24N, -115.81W'
 30 
 31 >>> c = 3-5j
 32 
 33 >>> ('The complex number {0} is formed from the real part {0.real} '
 34 
 35 ...  'and the imaginary part {0.imag}.').format(c)
 36 
 37 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
 38 
 39 >>> class Point(object):
 40 
 41 ...     def __init__(self, x, y):
 42 
 43 ...         self.x, self.y = x, y
 44 
 45 ...     def __str__(self):
 46 
 47 ...         return 'Point({self.x}, {self.y})'.format(self=self)
 48 
 49 ...
 50 
 51 >>> str(Point(4, 2))
 52 
 53 'Point(4, 2)
 54 
 55 >>> coord = (3, 5)
 56 
 57 >>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
 58 
 59 'X: 3;  Y: 5'
 60 
 61 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
 62 
 63 "repr() shows quotes: 'test1'; str() doesn't: test2"
 64 
 65 >>> '{:<30}'.format('left aligned')
 66 
 67 'left aligned                  '
 68 
 69 >>> '{:>30}'.format('right aligned')
 70 
 71 '                 right aligned'
 72 
 73 >>> '{:^30}'.format('centered')
 74 
 75 '           centered           '
 76 
 77 >>> '{:*^30}'.format('centered')  # use '*' as a fill char
 78 
 79 '***********centered***********'
 80 
 81 >>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
 82 
 83 '+3.140000; -3.140000'
 84 
 85 >>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
 86 
 87 ' 3.140000; -3.140000'
 88 
 89 >>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
 90 
 91 '3.140000; -3.140000'
 92 
 93 >>> # format also supports binary numbers
 94 
 95 >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
 96 
 97 'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
 98 
 99 >>> # with 0x, 0o, or 0b as prefix:
100 
101 >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
102 
103 'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
104 
105 >>> '{:,}'.format(1234567890)
106 
107 '1,234,567,890'
108 
109 >>> points = 19.5
110 
111 >>> total = 22
112 
113 >>> 'Correct answers: {:.2%}.'.format(points/total)
114 
115 'Correct answers: 88.64%'
116 
117 >>> import datetime
118 
119 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
120 
121 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
122 
123 '2010-07-04 12:15:58'
124 
125 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
126 
127 ...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
128 
129 ...
130 
131 'left<<<<<<<<<<<<'
132 
133 '^^^^^center^^^^^'
134 
135 '>>>>>>>>>>>right'
136 
137 >>>
138 
139 >>> octets = [192, 168, 0, 1]
140 
141 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
142 
143 'C0A80001'
144 
145 >>> int(_, 16)
146 
147 3232235521
148 
149 >>>
150 
151 >>> width = 5
152 
153 >>> for num in range(5,12):
154 
155 ...     for base in 'dXob':
156 
157 ...         print '{0:{width}{base}}'.format(num, base=base, width=width),
158 
159 ...     print
160 
161 ...
162 
163 5 5 5 101
164 
165 6 6 6 110
166 
167 7 7 7 111
168 
169 8 8 10 1000
170 
171 9 9 11 1001
172 
173 10 A    12 1010
174 
175 11 B    13 1011
176 
177 >>> from string import Template
178 
179 >>> s = Template('$who likes $what')
180 
181 >>> s.substitute(who='tim', what='kung pao')
182 
183 'tim likes kung pao'
184 
185 >>> d = dict(who='tim')
186 
187 >>> Template('Give $who $100').substitute(d)
188 
189 Traceback (most recent call last):
190 
191 [...]
192 
193 ValueError: Invalid placeholder in string: line 1, col 10
194 
195 >>> Template('$who likes $what').substitute(d)
196 
197 Traceback (most recent call last):
198 
199 [...]
200 
201 KeyError: 'what'
202 
203 >>> Template('$who likes $what').safe_substitute(d)
204 
205 'tim likes $what'

 

 

 1 string.capitalize(word) 返回一个副本,首字母大写
 2 
 3 >>> string.capitalize("hello")
 4 
 5 'Hello'
 6 
 7 >>> string.capitalize("hello world")
 8 
 9 'Hello world'
10 
11 >>> string.split("asdadada asdada")
12 
13 ['asdadada', 'asdada']
14 
15 >>> string.strip("              adsd         ")
16 
17 'adsd'
18 
19 >>> string.rstrip("              adsd         ")
20 
21 '              adsd'
22 
23 >>> string.lstrip("              adsd         ")
24 
25 'adsd         '
26 
27 string.swapcase(s) 小写变大写,大写变小写
28 
29 >>> string.swapcase("Helloo")
30 
31 'hELLOO'
32 
33 >>> string.ljust("ww",20)
34 
35 'ww                  '
36 
37 >>> string.rjust('ww',20)
38 
39 '                  ww'
40 
41 >>> string.center('ww',20)
42 
43 '         ww         '
44 
45 string.zfill(s, width)
46 
47 Pad a numeric string on the left with zero digits until the given width is reached. Strings starting with a sign are handled correctly.
48 
49 >>> string.zfill('ww',20)
50 
51 '000000000000000000ww'