Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

an elegant way to concatenate a list of chars in a string in Python [duplicate]

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.

like image 668
Yulia V Avatar asked Jan 30 '26 08:01

Yulia V


2 Answers

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'
like image 197
Óscar López Avatar answered Feb 01 '26 22:02

Óscar López


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

like image 36
Jon Clements Avatar answered Feb 01 '26 23:02

Jon Clements



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!