python 字符串

key point:  字符串都是不可改变的

打印:

>>> values
('world', 'hot')
>>> format
'hello, %s. %s enough for ya'
>>> print(format % values)
hello, world. hot enough for ya

>>> '%s plus %s equals %s' % (1, 1, 2)
'1 plus 1 equals 2'

>>> 'Using str %r' % 42
'Using str 42'

>>> 'Using str %r' % 42
'Using str 42'
>>> '%10f' %pi
' 3.141593'
>>> '%10.2f' % pi
' 3.14'
>>> '%.2f' % pi
'3.14'
>>> '%.5s' % 'Guido van rossum'
'Guido'

>>> '%010.2f' % pi
'0000003.14'

字符串操作方法:find

>>> title = "Monty Python's Flying Circus"
>>> title.find('Python')
6

字符串操作方法:join

>>> '+'.join(['1', '2', '3', '4', '5'])
'1+2+3+4+5'
>>> dirs = '', 'usr','bin','env'
>>> '/'.join(dirs)
'/usr/bin/env'

字符串操作方法: lower title capitalize swapcase

>>> 'test'.islower()
True
>>> 'test'.titla()
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'str' object has no attribute 'titla'
>>> 'test'.title()
'Test'
>>> 'test'.capitalize()
'Test'
>>> 'test'.swapcase()
'TEST'

字符串操作方法:replace

>>> 'THis is a test'.replace('is','eez')
'THeez eez a test'

字符串操作方法: split

>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']

字符串操作方法:strip()

>>> ' pan is pan '.strip()
'pan is pan'

字符串操作方法:translate

python3.7 not support

原文地址:https://www.cnblogs.com/lianghong881018/p/11077617.html