Convert all strings in a list to int
You can easily convert string list items into int items using loop shorthand in python
Say you have a string result = ['1','2','3']
Just do,
result = [int(item) for item in result]
print(result)
It'll give you output like
[1,2,3]
Use a list comprehension on the list xs
:
[int(x) for x in xs]
e.g.
>>> xs = ["1", "2", "3"]
>>> [int(x) for x in xs]
[1, 2, 3]
If your list contains pure integer strings, the accepted answer is the way to go. It will crash if you give it things that are not integers.
So: if you have data that may contain ints, possibly floats or other things as well - you can leverage your own function with errorhandling:
def maybeMakeNumber(s):
"""Returns a string 's' into a integer if possible, a float if needed or
returns it as is."""
# handle None, "", 0
if not s:
return s
try:
f = float(s)
i = int(f)
return i if f == i else f
except ValueError:
return s
data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]
converted = list(map(maybeMakeNumber, data))
print(converted)
Output:
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
To also handle iterables inside iterables you can use this helper:
from collections.abc import Iterable, Mapping
def convertEr(iterab):
"""Tries to convert an iterable to list of floats, ints or the original thing
from the iterable. Converts any iterable (tuple,set, ...) to itself in output.
Does not work for Mappings - you would need to check abc.Mapping and handle
things like {1:42, "1":84} when converting them - so they come out as is."""
if isinstance(iterab, str):
return maybeMakeNumber(iterab)
if isinstance(iterab, Mapping):
return iterab
if isinstance(iterab, Iterable):
return iterab.__class__(convertEr(p) for p in iterab)
data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed",
("0", "8", {"15", "things"}, "3.141"), "types"]
converted = convertEr(data)
print(converted)
Output:
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed',
(0, 8, {'things', 15}, 3.141), 'types'] # sets are unordered, hence diffrent order
Given:
xs = ['1', '2', '3']
Use map
then list
to obtain a list of integers:
list(map(int, xs))
In Python 2, list
was unnecessary since map
returned a list:
map(int, xs)