11

Whats the best way to convert int's, long's, double's to strings and vice versa in python.

I am looping through a list and passing longs to a dict that should be turned into a unicode string.

I do

for n in l:  
    {'my_key':n[0],'my_other_key':n[1]}

Why are some of the most obvious things so complicated?

3
  • 1
    "passing longs to a dict that should be turned into a unicode string"? How is that "obvious"? What are you trying to accomplish? Commented Mar 3, 2010 at 22:08
  • In JAVA, you can call the toString() method which you might think is obviously available in Python. And it does exist in Python via the str() method. Just not on the Object itself. Commented Mar 3, 2010 at 22:44
  • 1
    "not on the Object itself". str( anything ) works for every type there is -- by definition. For your own classes, def __str__(self) to tailor what is returned (it's like Java's toString) What actual problem are you having? Can you provide code and sample output? Commented Mar 4, 2010 at 1:39

3 Answers 3

38

To convert from a numeric type to a string:

str(100)

To convert from a string to an int:

int("100")

To convert from a string to a float:

float("100")
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I found it in the docs. But I appreciate your answer very much.
This is a much better answer. I don't know why it's not the accepted answer.
@ScottDavidTesler I think I am the only that repeatedly said that lines in SO ;)
2

You could do it like this in Python 2.x:

>>> l = ((1,2),(3,4))
>>> dict(map(lambda n: (n[0], unicode(n[1])), l))
{1: u'2', 3: u'4'}

or in Python 3.x:

>>> l = ((1,2),(3,4))
>>> {n[0] : str(n[1]) for n in l}
{1: '2', 3: '4'}

Note that strings in Python 3 are the same as unicode strings in Python 2.

2 Comments

The way the OP uses n[0] doesn't look like it's a key
This cide, while a working one, is also very hard to read. Code is read more than it is written, and that's why you should use code from Mark Byers answer.
0

You can do it this way

for n in l:
    {'my_key':unicode(n[0]),'my_other_key':unicode(n[1])}

Perhaps this is clearer if there are only 2 or 3 keys/values

for my_value, my_other_value in l:
    {'my_key':unicode(my_value),'my_other_key':unicode(my_other_value)}

I think this would be better if there are more than 3 keys/values

for n in l:
    dict(zip(('my_key','myother_key'),map(unicode,n)))

Comments

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.