字符串常用函数

1 字符串创建:var1 = 'Hello World!'

2 字符串不可变

3 单字符也在Python也是作为一个字符串使用

4 Python 访问子字符串,可以使用方括号来截取字符串

var1 = 'Hello World!'
var2 = "Runoob"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])

5 字符串转义:在需要在字符中使用特殊字符时,python用反斜杠(\)转义字符

6 字符串运算

+ 字符串连接

* 重复输出字符串

[] 通过索引取字符串中字符

[:] 截取字符串中部分字符

in 如果字符串中包含给定字符则返回true

not in 如果字符串中不包含给定字符则返回true

r/R 原始字符串 - 原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母"r"(可以大小写)以外,与普通字符串有着几乎完全相同的语法。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1 判断从控制台输入的字符串是否是数字

str = input("please input the number:")

if str.isdigit():

为True表示输入的所有字符都是数字,否则,不是全部为数字

str为字符串 str.isalnum() 所有字符都是数字或者字母 str.isalpha() 所有字符都是字母 str.isdigit() 所有字符都是数字 str.islower() 所有字符都是小写 str.isupper() 所有字符都是大写 str.istitle() 所有单词都是首字母大写,像标题 str.isspace() 所有字符都是空白字符、\t、\n、\r

 

 

https://www.cnblogs.com/rollenholt/archive/2011/11/25/2263722.html

  1 >>> import string
  2 >>> string.ascii_letters
  3 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  4 >>> string.ascii_lowercase
  5 'abcdefghijklmnopqrstuvwxyz'
  6 >>> string.ascii_uppercase
  7 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  8 >>> string.digits
  9 '0123456789'
 10 >>> string.hexdigits
 11 '0123456789abcdefABCDEF'
 12 >>> string.letters
 13 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
 14 >>> string.lowercase
 15 'abcdefghijklmnopqrstuvwxyz'
 16 >>> string.uppercase
 17 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 18 >>> string.octdigits
 19 '01234567'
 20 >>> string.punctuation
 21 '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
 22 >>> string.printable
 23 '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
 24 >>> string.whitespace
 25 '\t\n\x0b\x0c\r
 26  
 27 

143 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
144 'a, b, c'
145 >>> '{}, {}, {}'.format('a', 'b', 'c')  # 2.7+ only
146 'a, b, c'
147 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
148 'c, b, a'
149 >>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
150 'c, b, a'
151 >>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
152 'abracadabra'
153  
154 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
155 'Coordinates: 37.24N, -115.81W'
156 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
157 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
158 'Coordinates: 37.24N, -115.81W'
159  
160 >>> c = 3-5j
161 >>> ('The complex number {0} is formed from the real part {0.real} '
162 ...  'and the imaginary part {0.imag}.').format(c)
163 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
164 >>> class Point(object):
165 ...     def __init__(self, x, y):
166 ...         self.x, self.y = x, y
167 ...     def __str__(self):
168 ...         return 'Point({self.x}, {self.y})'.format(self=self)
169 ...
170 >>> str(Point(4, 2))
171 'Point(4, 2)
172  
173 >>> coord = (3, 5)
174 >>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
175 'X: 3;  Y: 5'
176  
177 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
178 "repr() shows quotes: 'test1'; str() doesn't: test2"
179  
180 >>> '{:<30}'.format('left aligned')
181 'left aligned                  '
182 >>> '{:>30}'.format('right aligned')
183 '                 right aligned'
184 >>> '{:^30}'.format('centered')
185 '           centered           '
186 >>> '{:*^30}'.format('centered')  # use '*' as a fill char
187 '***********centered***********'
188  
189 >>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
190 '+3.140000; -3.140000'
191 >>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
192 ' 3.140000; -3.140000'
193 >>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
194 '3.140000; -3.140000'
195  
196 >>> # format also supports binary numbers
197 >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
198 'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
199 >>> # with 0x, 0o, or 0b as prefix:
200 >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
201 'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
202  
203 >>> '{:,}'.format(1234567890)
204 '1,234,567,890'
205  
206 >>> points = 19.5
207 >>> total = 22
208 >>> 'Correct answers: {:.2%}.'.format(points/total)
209 'Correct answers: 88.64%'
210  
211 >>> import datetime
212 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
213 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
214 '2010-07-04 12:15:58'
215  
216 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
217 ...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
218 ...
219 'left<<<<<<<<<<<<'
220 '^^^^^center^^^^^'
221 '>>>>>>>>>>>right'
222 >>>
223 >>> octets = [192, 168, 0, 1]
224 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
225 'C0A80001'
226 >>> int(_, 16)
227 3232235521
228 >>>
229 >>> width = 5
230 >>> for num in range(5,12):
231 ...     for base in 'dXob':
232 ...         print '{0:{width}{base}}'.format(num, base=base, width=width),
233 ...     print
234 ...
235     5     5     5   101
236     6     6     6   110
237     7     7     7   111
238     8     8    10  1000
239     9     9    11  1001
240    10     A    12  1010
241    11     B    13  1011
242  
243 >>> from string import Template
244 >>> s = Template('$who likes $what')
245 >>> s.substitute(who='tim', what='kung pao')
246 'tim likes kung pao'
247 >>> d = dict(who='tim')
248 >>> Template('Give $who $100').substitute(d)
249 Traceback (most recent call last):
250 [...]
251 ValueError: Invalid placeholder in string: line 1, col 10
252 >>> Template('$who likes $what').substitute(d)
253 Traceback (most recent call last):
254 [...]
255 KeyError: 'what'
256 >>> Template('$who likes $what').safe_substitute(d)
257 'tim likes $what'
258  
259 
260 1
261 2
262 3
263 4
264 5
265 6
266 7
267 8
268 9
269 10
270 11
271 12
272 13
273 14
274 15
275 16
276 17
277 18
278 19
279 20
280 21
281 22
282 23
283 24
284 25
285 26
286 27
287 28
288 29
289 30
290 string.capitalize(word) 返回一个副本,首字母大写
291 >>> string.capitalize("hello")
292 'Hello'
293 >>> string.capitalize("hello world")
294 'Hello world'
295  
296 >>> string.split("asdadada asdada")
297 ['asdadada', 'asdada']
298  
299 >>> string.strip("              adsd         ")
300 'adsd'
301 >>> string.rstrip("              adsd         ")
302 '              adsd'
303 >>> string.lstrip("              adsd         ")
304 'adsd         '
305  
306 string.swapcase(s) 小写变大写,大写变小写
307 >>> string.swapcase("Helloo")
308 'hELLOO'
309  
310 >>> string.ljust("ww",20)
311 'ww                  '
312 >>> string.rjust('ww',20)
313 '                  ww'
314 >>> string.center('ww',20)
315 '         ww         '
316 string.zfill(s, width)
317 Pad a numeric string on the left with zero digits until the given width is reached. Strings starting with a sign are handled correctly.
318 >>> string.zfill('ww',20)
319 '000000000000000000ww'

 

posted @ 2017-12-16 23:40  林雁1983  阅读(354)  评论(0)    收藏  举报