Convert a list of characters into a string
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Ancient Construction
--
Chapters
00:00 Convert A List Of Characters Into A String
00:12 Accepted Answer Score 697
00:26 Answer 2 Score 49
01:16 Answer 3 Score 11
01:27 Answer 4 Score 21
01:50 Thank you
--
Full question
https://stackoverflow.com/questions/4481...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string
#avk47
ACCEPTED ANSWER
Score 697
Use the join method of the empty string to join all of the strings together with the empty string in between, like so:
>>> a = ['a', 'b', 'c', 'd']
>>> ''.join(a)
'abcd'
ANSWER 2
Score 49
This works in many popular languages like JavaScript and Ruby, why not in Python?
>>> ['a', 'b', 'c'].join('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'
Strange enough, in Python the join method is on the str class:
# this is the Python way
"".join(['a','b','c','d'])
Why join is not a method in the list object like in JavaScript or other popular script languages? It is one example of how the Python community thinks. Since join is returning a string, it should be placed in the string class, not on the list class, so the str.join(list) method means: join the list into a new string using str as a separator (in this case str is an empty string).
Somehow I got to love this way of thinking after a while. I can complain about a lot of things in Python design, but not about its coherence.
ANSWER 3
Score 21
If your Python interpreter is old (1.5.2, for example, which is common on some older Linux distributions), you may not have join() available as a method on any old string object, and you will instead need to use the string module. Example:
a = ['a', 'b', 'c', 'd']
try:
b = ''.join(a)
except AttributeError:
import string
b = string.join(a, '')
The string b will be 'abcd'.
ANSWER 4
Score 11
This may be the fastest way:
>> from array import array
>> a = ['a','b','c','d']
>> array('B', map(ord,a)).tostring()
'abcd'