Showing posts with label float(). Show all posts
Showing posts with label float(). Show all posts

Wednesday, May 13, 2009

Convert Strings to Integers/Floats in Python

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]