python中没有破坏的空格

H.A*_*H.A 5 python

为什么python不删除非破坏的空格.strip(' ')但是.split(' ')在字符上拆分?

And*_*den 4

首先,这些函数执行两个不同的任务:

'      foo    bar    '.split() is ['foo','bar']
#a list of substrings without any white space (Note the default is the look for whitespace - see below)
'      foo    bar    '.strip() is 'foo    bar'
#the string without the beginning and end whitespace
Run Code Online (Sandbox Code Playgroud)

strip(' ')当仅使用开头和结尾处的空格strip()时,尽管非常相似但并不完全相同,例如制表符\t是空格但不是空格:

'   \t   foo   bar  '. strip()    is 'foo   bar'
'   \t   foo   bar  '. strip(' ') is '\t   foo   bar'
Run Code Online (Sandbox Code Playgroud)

split(' ')与将字符串拆分为针对每个“空格”的列表相比,使用它时,split()它将字符串“拆分”为针对每个空格的列表。考虑'foo bar'(foo 和 bar 之间有两个空格)。

'foo  bar'.split()    is ['foo', 'bar']
#Two spaces count as only one "whitespace"
'foo  bar'.split(' ') is ['foo', '', 'bar']
#Two spaces split the list into THREE (seperating an empty string)
Run Code Online (Sandbox Code Playgroud)

微妙之处在于两个空格或多个空格和制表符被视为“一个空格”。

  • “strip 和 split 的默认参数都是空格”:这是不对的。比较 `"a b".split()` 和 `"a b".split(" ")` ["a" 和 "b" 之间有两个空格],或者 `"a\tb".split(" " )` vs `"a\tb".split()`。 (2认同)