strip与split比较

strip

strip(self, chars=None, /)
Return a copy of the string with leading and trailing whitespace remove.
If chars is given and not None, remove characters in chars instead

将字符串按所给的值进行切割,并以字符串的形式返回,当不传入值时,char默认为空,与之对应的有rstriplstrip,左切割与右切割。

>>> s = '     22    '
>>> s.strip()
'22'
>>> s.rstrip()
'     22'
>>> s.lstrip()
'22    '

当传入的值不在两端时,则不进行切割,返回整个值

>>> s = '1112421421512435124121'
>>> s.strip()
'1112421421512435124121'
>>> s.strip('1')
'242142151243512412'
>>> s.rstrip('2')
'1112421421512435124121'
>>> s.rstrip('1')
'111242142151243512412'
>>> s.lstrip('1')
'2421421512435124121'

split

split(self, /, sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string.

sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.

将字符串按照所给的值进行切片,并以列表值返回。如果什么都没传入,则默认为空字符。maxsplit是最多切几次,同样相似的函数有rsplitlsplit

s = '1241221122124125121'
>>> s.split('1')
['', '24', '22', '', '22', '24', '25', '2', '']
>>> s.split('2')
['1', '41', '', '11', '', '1', '41', '51', '1']
>>> s.split('1',2)
['', '24', '221122124125121']
>>> s = '    125 11   '
>>> s.strip()
'125 11'
>>> s.split()
['125', '11']

两者的用途

split:当用户输入两个数字时,使用该函数进行逐个拿取
sprit:如果需要用户输入的数字是一个两边不包含特定字符时,可以使用该函数
strip函数的使用

>>> n = input().strip()
  1 2 3   
>>> n
'1 2 3'

split函数的使用

>>> n = input().split()
  1 2 22
>>> n
['1', '2', '22']
>>> a,b,c = input().split()
  1 2  2222     
>>> a
'1'
>>> b
'2'
>>> c
'2222'
发布了106 篇原创文章 · 获赞 21 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/jiangSummer/article/details/104922489