字符串的处理方法

2019-12-28  本文已影响0人  August________

字符串的处理方法

center

>>> "The Middle by Jimmy Eat World".center(39)
'     The Middle by Jimmy Eat World     '
>>> "The Middle by Jimmy Eat World".center(39, "*")
'*****The Middle by Jimmy Eat World*****'

find

>>> 'With a moo-moo here,and a moo-moo there'.find('moo')
7
>>> title = 'python is a language'
>>> title.find("is")
7
>>> title.find("python")
0
>>> title.find('abc')
-1

join

>>> seq = ['1', '2', '3', '4', '5', '6']
>>> sep = '+'
>>> sep.join(seq)
'1+2+3+4+5+6'
>>> dirs = '', 'usr', 'bin', 'env'
>>> dirs
('', 'usr', 'bin', 'env')
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print("C:" + '/'.join(dirs))
C:/usr/bin/env

lower

>>> "Hello World".lower()
'hello world'

title

>>> 'hello world'.title()
'Hello World'

replace

>>> 'this is a test'.replace('is', 'eez')
'theez eez a test'

split

>>> '1+2+3+4+5+6'.split("+")
['1', '2', '3', '4', '5', '6']
>>> '/usr/bin/env'.split("/")
['', 'usr', 'bin', 'env']

strip

>>> '      hello world           '.strip()
'hello world'

translate

>>> table = str.maketrans('cs', 'kz')
>>> table
{99: 107, 115: 122}
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
上一篇 下一篇

猜你喜欢

热点阅读