Possible Duplicate:
How can I optimally concat a list of chars to a string?
I have a list of chars:
['h', 'e', 'l', 'l', 'o']
Is there a way to concatenate the elements of such list in a string 'hello' that does not require c-like 'for' loop? Thanks.
This is the usual way of concatenating strings in Python:
''.join(list_of_chars)
In fact, that's the recommended way - for readability and efficiency reasons. For example:
''.join(['h', 'e', 'l', 'l', 'o'])
=> 'hello'
str.join
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>> ''.join(_)
'hello'
It's effectively:
from operator import add
reduce(add, ['h', 'e', 'l', 'l', 'o'])
But optimised for strings, it also only allows strings, otherwise it raises a TypeError
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With