Last answered:

05 Nov 2024

Posted on:

02 Nov 2024

0

Resolved: .split() differences

Wat is the difference between .split(", "), .split(" ") and split() ?
2 answers ( 0 marked as helpful)
Instructor
Posted on:

05 Nov 2024

0

Hi Lenka,

The .split() method for strings will separate a full string into many different substrings based on the provided parameter. It is easier to eplain through exampes.

If you use .split(" ") on a string, you are telling Python to split the string whenever it encounters a space " ".
Imagine you have this string: s = "This is an example string!"
s.split(" ") will return the following result:
['This', 'is', 'an', 'example', 'string!']
Here, Python has identified every space " " in the original string and gave us the strings to the left and right of it.

.split(", ") does the same, however for the combination of a comma and a space.
For example, let's say we have this string s = "This is a string, as well!"
s.split(", ") will return the following result:
['This is a string', 'as well!']

You can split using whatever combination of characters you want. For example, a somewhat silly split might be using the character "s".
s.split("s") will result in:
['Thi', ' i', ' a ', 'tring, a', ' well!']
Notice that this time, no whitespace has been removed.

As you can see, we are just separating the Python string based on the separator parameter written between the parenteses. Sometimes, however, there might be some edge cases that are unhelpful.
For example, in this string s = "There is a  double space here.", I have included a double space between "a" and "double". If we run s.split(" "), the result would be:
['There', 'is', 'a', '', 'double', 'space', 'here.']

This includes an empty string '' between 'a' and 'double'. That's because we are spliting the string on every space, and between the two spaces we have nothing - this is interpreted as an empty string '' by Python.

In order to obtain proper results when there are multiple consecutive spaces, we can use .split() without specifying any separator.
s.split() will return:
['There', 'is', 'a', 'double', 'space', 'here.']

Hope this helps you grasp the difference between these split() methods.

Best,
Nikola, 365 Team

Posted on:

05 Nov 2024

0
Thank you, I understand now.

Submit an answer