Reputation: 1173
As an exercise, describe the relationship
between string.join(string.split(song)) and song.
(they both refer to a string)
Are they the same for all strings? When would they be different?
I am a little ashamed to ask such a question for a likely simple question but,
I don't get it, what is/are the exception(s)? when are they are different?
Upvotes: 1
Views: 360
Reputation: 26586
split
actually splits on one or more occurrences of the delimiter. So " a b c ".split()
and "a b c".split() both result in the same list
i.e. ['a','b','c']
. join
only adds a single instance of the delimiter in between consecutive elements of the list
. " ".join(['a','b','c'])gives us
"a b c"`, which matches out second string but not the first string.
>>> original=" a b c "
>>> " ".join(original.split())
'a b c'
BTW, using string.split
and string.join
is deprecated. Simply call them as methods of the string you are working on (as in my examples).
Upvotes: 1
Reputation: 193716
By default the split
method groups consecutive delimiters together, so if you have them in your original string they'll be lost:
>>> import string
>>> song = "I am the Walrus"
>>> string.join(string.split(song))
'I am the Walrus'
However, if you specify delimiters to split on then consecutive delimiters are not grouped so you can keep the strings the same:
>>> string.join(string.split(song,' '))
'I am the Walrus'
Upvotes: 3