Pythonic List To String Method
Solution 1:
No, that is the pythonic way to do it.
Maybe you feel that it should read: string_list.join('')
. You are not alone.
Probably the most important advantage is, that this enables .join()
to work with anything that is iterable.
If it worked the other way around, each collection would need to implement a join()
method by themselves. If you were to create your own collection, would you add a .join()
method? Probably not.
The fact that it is a method of the str
class means, that it will always work. There are no surprises. Read here on Python and the principle of least astonishment about join()
and other things by the Flask
author Armin Ronacher.
A similar argument can be made for the len()
function/operator, which can be found at the beginning of the aforementioned article.
Solution 2:
Use ''.join(string_list)
. Note that list
names a built-in type, so you should not use that for variable names. Since Python strings are immutable, you need to construct a new string regardless. ''.join(s)
is the canonical and efficient way to do this in Python.
Solution 3:
I think you're overcomplicating. Here is from python itself:
>>> list = ['h', 'e', 'l', 'l', 'o']
>>>sum(list, '')
Traceback (most recent calllast):
File "<stdin>", line 1, in<module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]
So, python's recommendation is to use ''.join
.
Post a Comment for "Pythonic List To String Method"