Python学习笔记之字符串截取

发布时间:2020-11-04编辑:脚本学堂
本文介绍下,有关python对字符串截取的一些知识,希望对大家有所帮助。

pythonzifuchuan/ target=_blank class=infotextkey>python字符串截取,可以借助下面的方法:
 

str[0:5] 截取第一位到第四位的字符
str[:] 截取字符串的全部字符
str[4:] 截取第五个字符到结尾
str[:-3] 截取从头开始到倒数第三个字符之前
str[2] 截取第三个字符
str[::-1] 创造一个与原字符串顺序相反的字符串

附,python 字符串的分割和组合
 

>>> 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序列串联起来