Can someone explain to me why in python when we want to join a string we write:
'delim'.join(list)
and when we want to split a string we write:
str.split('delim')
coming from java it seems that one of these is backwards because in java we write:
//split:
str.split('delim');
//join
list.join('delim');
edit:
you are right. join takes a list. (though it doesnt change the question)
Can someone explain to me the rationale behind this API?
Join only makes sense when joining some sort of iterable. However, since iterables don’t necessarily contain all strings, putting
joinas a method on an iterable doesn’t make sense. (what would you expect the result of[1,"baz",my_custom_object,my_list].join("foo")to be?) The only other place to put it is as a string method with the understanding that everything in the iterable is going to be a string. Additionally, puttingjoinas a string method allows it to be used with any iterable — tuples, lists, generators, custom objects which support iteration or even strings.Also note that you are completely free to split a string in the same way that you join it:
Of course, the utility here isn’t quite as easy to see.