+ 2

Split in python 3

Why in this code, after omitting 'e' by split we have following result ? ['Comput', 'r sci', 'nc', ' '] While The 'e' after 'c' omitted and ' ' remained, but by omitting 'e' between 't' and 'r' there is no ' ' remained; why ? https://code.sololearn.com/cDG00Df301gS/#py

14th Dec 2017, 3:50 PM
NIMA
NIMA - avatar
5 Antworten
+ 6
When string.split("separator") encounters a separator, it creates two strings. The left string ends just before the separator and the right string begins right after the separator. If your string starts or ends with a separator, the left or right string will be empty, respectively - i.e. ' ' (with no space between the single quotes). To see this, try your code with "end game".
15th Dec 2017, 9:48 AM
David Ashton
David Ashton - avatar
+ 5
Because otherwise you lose the information that there was an 'e' at the end of science. And therefore would not be able to generate the original string back.
14th Dec 2017, 4:01 PM
Zandifier
Zandifier - avatar
+ 3
Think of it as replacing an e with a comma. You'll get it
14th Dec 2017, 3:59 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 3
It's a fascinating problem. The method seems to create an empty string whenever it encounters a string ending in a separator, and when it encounters a double separator, it removes one, creating a string ending in a separator, which results in an empty string. If the double separator is internal, e.g. 'seem', you get one empty string.
15th Dec 2017, 11:10 AM
David Ashton
David Ashton - avatar
+ 1
Thanks for your description it is interesting that if have extra 'e' at the end of string ... by trying code with "computer sciencee"
15th Dec 2017, 11:00 AM
NIMA
NIMA - avatar