Question

I am reading a book and below is a small code provided in it:

>>>S='shrubbery'
>>>L=list(S)
>>>L
>>>['s', 'h', 'r', 'u', 'b', 'b', 'e', 'r', 'y']
>>>L[1]='c'
>>>''.join(L)
'scrubbery'

Can someone explain me the syntax of last command ''.join(L) I understand what's its doing ..but its kind of weird ... which one is object or class in this command? is '' a string object and join()the method ....

thanks

Was it helpful?

Solution

See the docs:

str.join(iterable)

Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string (str) providing this method.

So ''.join(L) joins the elements of L, separating them from each other by the empty string.

You might wonder why this method seems so backwards (for example, why not L.join('')? The reason is simple: The result will always be a string, and the separator will always be a string. And since the method should work on any iterable that can provide a string representation of its members, it makes sense to define it once on the string separator instead of multiple times for each possible iterable.

OTHER TIPS

The join method of a string str causes the list of strings passed to it to be joined into a single string using the str string, i.e. ','.join(['1', '2', '3']) will return '1,2,3'.

'' is an empty string, thus the list of strings will be joined using an empty delimiter, i.e. ''.join(['1', '2', '3']) returns '123'.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top