Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list to string [duplicate]

How can I convert a list to a string using Python?

like image 433
Nm3 Avatar asked Apr 11 '11 08:04

Nm3


People also ask

How do I convert a list to a string?

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 convert a list to a string in Java?

We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.

How do you convert a list to a comma separated string in Python?

Use the join() Function to Convert a List to a Comma-Separated String in Python. The join() function combines the elements of an iterable and returns a string. We need to specify the character that will be used as the separator for the elements in the string.

How do I turn a list into a tuple?

1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.


2 Answers

>>> L = [1,2,3]        >>> " ".join(str(x) for x in L) '1 2 3' 
like image 28
Andrey Sboev Avatar answered Sep 28 '22 04:09

Andrey Sboev


By using ''.join

list1 = ['1', '2', '3'] str1 = ''.join(list1) 

Or if the list is of integers, convert the elements before joining them.

list1 = [1, 2, 3] str1 = ''.join(str(e) for e in list1) 
like image 186
Senthil Kumaran Avatar answered Sep 28 '22 03:09

Senthil Kumaran