Why does split() return more elements than split(“ ”) on same string?

前端 未结 5 1708
闹比i
闹比i 2021-01-15 03:52

I am using split() and split(\" \") on the same string. But why is split(\" \") returning less number of elements than split()

5条回答
  •  长发绾君心
    2021-01-15 04:31

    The method str.split called without arguments has a somewhat different behaviour.

    First it splits by any whitespace character.

    'foo bar\nbaz\tmeh'.split() # ['foo', 'bar', 'baz', 'meh']
    

    But it also remove the empty strings from the output list.

    ' foo bar '.split(' ') # ['', 'foo', 'bar', '']
    
    ' foo bar '.split() # ['foo', 'bar']
    

提交回复
热议问题