Reputation: 29
I am new to Python. I need to know how to convert a list of integers to a list of strings. So,
>>>list=[1,2,3,4]
I want to convert that list to this:
>>>print (list)
['1','2','3','4']
Also, can I add a list of strings to make it look something like this?
1234
Upvotes: 0
Views: 1836
Reputation: 2216
l = map(str,l)
will work, but may not make sense if you don't know what map is
l = [str(x) for x in l]
May make more sense at this time.
''.join(["1","2","3"]) == "123"
Upvotes: 0
Reputation: 11686
Using print:
>>> mylist = [1,2,3,4]
>>> print ('{}'*len(mylist)).format(*mylist)
1234
Upvotes: 0
Reputation: 213253
You can use List Comprehension:
>>> my_list = [1, 2, 3, 4]
>>> [str(v) for v in my_list]
['1', '2', '3', '4']
or map()
:
>>> str_list = map(str, my_list)
>>> str_list
['1', '2', '3', '4']
In Python 3, you would need to use - list(map(str, my_list))
For 2nd part, you can use join()
:
>>> ''.join(str_list)
'1234'
And please don't name your list list
. It shadows the built-in list
.
Upvotes: 8
Reputation: 14619
>>>l=[1,2,3,4]
I've modified your example to not use the name list
-- it shadows the actual builtin list
, which will cause mysterious failures.
Here's how you make it into a list of strings:
l = [str(n) for n in l]
And here's how you make them all abut one another:
all_together = ''.join(l)
Upvotes: 2