Convert Strings to Integers/Floats in Python

Wednesday, May 13th, 2009
Advertisement

Subscribe.
Enter your email:

Strings to integer

To convert a string to an integer:

>>> x = '1234'
>>> int(x)
1234

Strings to float

To convert a string to float:

>>> x = '1234'
>>> float(x)
1234.0

>>> y = '1234.678'
>>> float(y)
1234.6780000000001

but, convertion of ‘1234.678′ to integer using int() will gives an error.

>>> int(y)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
int(y)
ValueError: invalid literal for int() with base 10: '1234.678'

A workaround is by first converting to float, then to integer:

>>> y = '1234.678'
>>> int(float(y))
1234

List/tuple of strings to list of integers

  1. Using list comprehension
    >>> x = ['07', '11', '13', '14', '28']
    >>> [int(i) for i in x]
    [7, 11, 13, 14, 28]
  2. Using map
    >>> x = ['07', '11', '13', '14', '28']
    >>> list(map(int, x))
    [7, 11, 13, 14, 28]

    Mix of integers and floats

    >>> x = ['7.424124', '11', '13.423', '14.53453656', '28.2']
    >>> list(map(int, map(float, x)))
    [7, 11, 13, 14, 28]

List/tuple of strings to list of floats

  1. Using list comprehension
    >>> x = ['7.424124', '1', '13.423', '14.53453656', '28.2']
    >>> [float(i) for i in x]
    [7.4241239999999999, 1.0, 13.423, 14.534536559999999, 28.199999999999999]
    
  2. Using map
    >>> x = ['7.424124', '1', '13.423', '14.53453656', '28.2']
    >>> list(map(float, x))
    [7.4241239999999999, 1.0, 13.423, 14.534536559999999, 28.199999999999999]
If you are new here, you might want to subscribe to the RSS feed or newsletter.

Enter your email address:

Creates the exact copy of your hard disk and allows you to instantly restore the entire machine.
New Acronis True Image Home 2010 is the most reliable and easy in use backup solution. Now with online backup option!
15% Discount Code: FMAATIH2010

What else?

Like this article? Share it

 Digg  del.icio.us  TwitThis  Facebook  Reddit  StumbleUpon

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>