Reputation: 1342
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?
Upvotes: 3
Views: 567
Reputation: 16905
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.
Upvotes: 5
Reputation: 8607
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.
Upvotes: 4
Reputation: 10493
I think you're overcomplicating. Here is from python itself:
>>> list = ['h', 'e', 'l', 'l', 'o']
>>> sum(list, '')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]
So, python's recommendation is to use ''.join
.
Upvotes: 2