0

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
0

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

map() returns a map object in Python 3. You need to do list(map(...)) to convert it into a list.
Thanks a lot Rohit! Learnt a lot from you!
2
>>>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)

1 Comment

Thanks a lot Brian! Learnt a lot from you!
0

Using print:

>>> mylist = [1,2,3,4]
>>> print ('{}'*len(mylist)).format(*mylist)
1234

Comments

0
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"

2 Comments

Do not use list as a reference's name, as it is the name of the built in list class. Doing so will cause much grieve later on!
Thanks a lot Peter! Learnt a lot from you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.