What is the difference between split(" ") and split()

Asked

Viewed 47 times

1

I’m manipulating strings and I came across this question. I thought the semantics of the ways to use was the same, but I saw that not and it left me confused.

In the case I thought with the use of split(" ") all space in the original string would be removed and I would have something like:

['07', '10', '11', '20', '30', '44', '34 n']

But what I got on the way out was:

palavra = "     07 10 11 20 30 44 34\n"

splt = palavra.split(" ")

print(splt)

return:

['', '', '', '', '', '07', '10', '11', '20', '30', '44', '34 n']

And with the use of split() came much closer than I expected.

palavra = "     07 10 11 20 30 44 34\n"

splt = palavra.split()

print(splt)

return:

['07', '10', '11', '20', '30', '44', '34']

1 answer

2


If you give the command below

print(help(palavra.split))

you will see the result below

Help on built-in function split:

split(sep=None, maxsplit=-1) method of builtins.str instance
    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.

Then see that " " (space) has the result different from None

None, ie the use of .split() discards empty strings.

I hope I’ve helped

  • 1

    Sorry, I don’t know if I got it right, so the split(" ") will only be removed actually when it is among other values, in my case the numbers. The split() will remove all being among other values or not, this?

  • 1

    @Shinforinpola split(" ") will separate the string in the spaces and keep everything you found (in your example, found "empty"), while split() will do the same thing at first and then discard these "voids".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.