Python3 —— 字符串分割

s.split([sep, [maxsplit]]) 以sep是分隔符,把s分割成一个list。sep默认为空格。maxsplit是分割的次数,默认是对整个s进行分割

str = 'This is a string. We want to split it!'
# 从前向后分割
str.split()
str.split(' ', 3)
str.split('s')

结果:
['This', 'is', 'a', 'string.', 'We', 'want', 'to', 'split', 'it!']

['This', 'is', 'a', 'string. We want to split it!']

['Thi', ' i', ' a ', 'tring. We want to ', 'plit it!']


s.rsplit([sep, [maxsplit]]) 和split()的区别是它是从s的串尾往前进行分割。

str = 'This is a string. We want to split it!'
# 从后向前分割
str.rsplit()
str.rsplit(' ', 3)
str.rsplit('s')

结果:
['This', 'is', 'a', 'string.', 'We', 'want', 'to', 'split', 'it!']

['This is a string. We want', 'to', 'split', 'it!']

['Thi', ' i', ' a ', 'tring. We want to ', 'plit it!']

猜你喜欢

转载自blog.csdn.net/Muzi_Water/article/details/81476393
今日推荐