Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list of numbers converted to string incorrectly

For some reason, when I do the code...

def encode():
    result2 = []
    print result  
    for x in result:  
        result2 += str(x)  
    print result2

I get...

[123, 456, 789]
['1', '2', '3', '4', '5', '6', '7', '8', '9']

How do I get it to return ['123', '456', '789']?

Thanks!

like image 405
JShoe Avatar asked Aug 05 '11 01:08

JShoe


People also ask

How do you convert a list of data to integers in Python?

Another approach to convert a list of multiple integers into a single integer is to use map() function of Python with str function to convert the Integer list to string list. After this, join them on the empty string and then cast back to integer.

How do I convert a list of numbers 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 you convert a list of numbers into a list of strings?

You can convert an integer list to a string list by using the expression list(map(str, a)) combining the list() with the map() function. The latter converts each integer element to a string.


2 Answers

How about:

result2 = [str(x) for x in result]

The reason you are getting what you are getting is the += is doing list concatenation. Since str(123) is '123', which can be seen as ['1', '2', '3'], when you concatenate that to the empty list you get ['1', '2', '3'] (same thing for the other values).

For it to work doing it your way, you'd need:

result2.append(str(x)) # instead of result2 += str(x)
like image 181
NullUserException Avatar answered Sep 25 '22 11:09

NullUserException


The functional method is to use list(map(str, lst)):

lst = [123, 456, 789]

res = list(map(str,  lst))

print(res)
# ['123', '456', '789']

Performance is slightly better than a list comprehension.

like image 34
jpp Avatar answered Sep 23 '22 11:09

jpp