Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list to string using python

Tags:

python

list

I have the list it contain int ,float and string:

lists = [10, "test", 10.5]

How Can i convert above list to string? I have tried:

val = ','.join(lists)
print val

I am getting error like this:

sequence item 0: expected string, int found

How can I solve this issue?

like image 221
Abdul Razak Avatar asked Nov 10 '15 12:11

Abdul Razak


People also ask

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 convert a list of numbers to string?

The most Pythonic way to convert a list of integers ints to a list of strings is to use the one-liner strings = [str(x) for x in ints] . It iterates over all elements in the list ints using list comprehension and converts each list element x to a string using the str(x) constructor.


2 Answers

Firstly convert integers to string using strusing map function then use join function-

>>> ','.join(map(str,[10,"test",10.5]) )#since added comma inside the single quote output will be comma(,) separated
>>> '10,test,10.5'

Or if you want to convert each element of list into string then try-

>>> map(str,[10,"test",10.5])
>>> ['10', 'test', '10.5']

Or use itertools for memory efficiency(large data)

>>>from itertools import imap
>>>[i for i in imap(str,[10,"test",10.5])]
>>>['10', 'test', '10.5']

Or simply use list comprehension

>>>my_list=['10', 'test', 10.5]
>>>my_string_list=[str(i) for i in my_list]
>>>my_string_list
>>>['10', 'test', '10.5']
like image 169
SIslam Avatar answered Oct 11 '22 11:10

SIslam


The easiest way is to send the whole thing to str() or repr():

>>> lists = [10, "test", 10.5]
>>> str(lists)
"[10, 'test', 10.5]"

repr() may produce a different result from str() depending on what's defined for each type of object in the list. The point of repr() is that you can send such strings back to eval() or ast.literal_eval() to get the original object back:

>>> import ast
>>> lists = [10, "test", 10.5]
>>> ast.literal_eval(repr(lists))
[10, 'test', 10.5]
like image 27
TigerhawkT3 Avatar answered Oct 11 '22 11:10

TigerhawkT3