Continuous space in python

Why doesn't python remove unused spaces on .strip(' ')but .split(' ')breaks into character?

+5
source share
1 answer

Firstly, these functions perform two different tasks:

'      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

.

When used strip(' '), only spaces at the beginning and end are removed , although it is very similar to strip(), it is not quite the same, for example, with a tab \tthat is a space, but isn 'a space:

'   \t   foo   bar  '. strip()    is 'foo   bar'
'   \t   foo   bar  '. strip(' ') is '\t   foo   bar'

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)

, " ".

+4

All Articles