Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collapse a list into a string in python? [duplicate]

Lets say you have a list like ['a', 'b', 'c'] and you want it to look like 'abc' and you don't want to use some big stupid looking for loop.

like image 663
AlanGhalan Avatar asked Jan 25 '14 19:01

AlanGhalan


People also ask

How do you collapse a list to a string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I join a list of elements into a string?

If you want to concatenate a list of numbers ( int or float ) into a single string, apply the str() function to each element in the list comprehension to convert numbers to strings, then concatenate them with join() .

How do I make a list of strings in one string in Python?

Use the join() Method to Convert the List Into a Single String in Python. The join() method returns a string in which the string separator joins the sequence of elements. It takes iterable data as an argument. We call the join() method from the separator and pass a list of strings as a parameter.


2 Answers

>>> str_list=['a','b','c']
>>> ''.join(str_list)
'abc'
like image 113
afkfurion Avatar answered Oct 19 '22 13:10

afkfurion


I think it's

string = ''.join(['a', 'b', 'c'])
like image 37
embert Avatar answered Oct 19 '22 15:10

embert