So I’m wondering what the most “pythonic” way of turning a list into a string.
For example:
string_list = ['h', 'e', 'l', 'l', 'o']
# to the string
string = 'hello'
I’ve been using the ''.join(string_list) method but it just feels near unreadable and roundabout method to do something so simple.
Is there a better way or am I overcomplicating this?
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
strclass means, that it will always work. There are no surprises. Read here on Python and the principle of least astonishment aboutjoin()and other things by theFlaskauthor Armin Ronacher.A similar argument can be made for the
len()function/operator, which can be found at the beginning of the aforementioned article.