Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I optimally concat a list of chars to a string?

Tags:

python

string

The data:

list = ['a','b','x','d','s']

I want to create a string str = "abxds". How can I do that?

Right now I am doing something like:

str = ""
for i in list:
    str = str + i
print(str)

I know strings are immutable in Python and this will create 7 string object. And this goes out of my memory when I do thousands of times.

Is there a more efficient way of doing this?

like image 485
rda3mon Avatar asked Dec 02 '22 04:12

rda3mon


2 Answers

>>> theListOfChars = ['a', 'b', 'x', 'd', 's']
>>> ''.join(theListOfChars)
'abxds'

BTW, don't use list or str as variable names as they are names of built-in functions already.

(Also, there is no char in Python. A "character" is just a string of length 1. So the ''.join method works for list of strings as well.)

like image 82
kennytm Avatar answered Dec 05 '22 03:12

kennytm


KennyTM's answer is great. Also, if you wanted to make them comma separated or something, it'd be:

",".join(characterlist)

This would result in "a,b,x,d,s"

like image 31
Chris Avatar answered Dec 05 '22 03:12

Chris