分类: Python/Ruby
2013-07-07 10:17:58
字符串的分割和组合
>>> s
'hello World!
Everyone! This Is My First String!'
>>> s.split()
['hello',
'World!', 'Everyone!', 'This', 'Is', 'My', 'First', 'String!']
>>>
s.split(' ',4)
['hello', 'World!', 'Everyone!', 'This', 'Is My First
String!']
>>> s.split('e')
['h', 'llo World! Ev', 'ryon', '! This
Is My First String!']
>>> s.rsplit()
['hello', 'World!',
'Everyone!', 'This', 'Is', 'My', 'First', 'String!']
>>> s.rsplit('
',4)
['hello World! Everyone! This', 'Is', 'My', 'First',
'String!']
>>> s.rsplit('e')
['h', 'llo World! Ev', 'ryon', '!
This Is My First String!']
#s.split([sep, [maxsplit]])
以sep是分隔符,把s分割成一个list。sep默认为空格。maxsplit是分割的次数,默认是对整个s进行分割
#s.rsplit([sep,
[maxsplit]]) 和split()的区别是它是从s的串尾往前进行分割
>>>
s=s.replace(' ','/n')
>>>
s
'hello/nWorld!/nEveryone!/nThis/nIs/nMy/nFirst/nString!'
>>>
s.splitlines()
['hello', 'World!', 'Everyone!', 'This', 'Is', 'My', 'First',
'String!']
>>> s.splitlines(True)
['hello/n', 'World!/n',
'Everyone!/n', 'This/n', 'Is/n', 'My/n', 'First/n', 'String!']
>>>
s.splitlines(False)
['hello', 'World!', 'Everyone!', 'This', 'Is', 'My',
'First', 'String!']
>>>
'/t'.join(s.splitlines())
'hello/tWorld!/tEveryone!/tThis/tIs/tMy/tFirst/tString!'
#s.splitlines([keepends])
把s按照行分隔符分成一个list。如果keepends为True则list的每个元素保留行分割符,如果为False则不保留分隔符
#s.join(seq)
用s把seq序列串联起来