Comparing Python's str.split()
with str.partition()
, I see that they not only have different functions (split()
tokenizes the whole string at each occurrence of the delimiter, while partition()
just returns everything before and everything after the first delimiter occurrence), but that they also have different return types. That is, str.split()
returns a list
while str.partition()
returns a tuple
. This is significant since a list
is mutable while a tuple
is not. Is there any deliberate reason behind this choice in the API design, or is it "just the way things are." I am curious.
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.
The split() breaks the string at the separator and returns a list of strings. If no separator is defined when you call upon the function, whitespace will be used by default.
Description. Python string method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.
The split() method breaks up a string at the specified separator and returns a list of strings.
The key difference between those methods is that split()
returns a variable number of results, and partition()
returns a fixed number. Tuples are usually not used for APIs which return a variable number of items.
@yole answer summarise the reasoning why partition()
returns tuple. But there is a nice way to "exploit" that fact. I found below example in "Automate the boring stuff with Python".
before, sep, after = 'Hello, world!'.partition(' ')
print(before)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With