Possible Duplicate: How to convert strings into integers in Python?
Hello guys,
I am trying to convert this string integers from a nested list to integers. This is my list:
listy = [['+', '1', '0'], ['-', '2', '0']]
I trying to convert to this:
[['+', 1, 2], ['-', 2, 0]]
This what I have tried so far, but my second line of code is taken from one of the answers in the question How to convert strings into integers in Python?
listy = [['+', '1', '0'], ['-', '2', '0']]
T2 = [list(map(int, x)) for x in listy]
print(T2)
But it gives me an error:
ValueError: invalid literal for int() with base 10: '+'
Is there any possible way to fix this in Python 3?
You could use isdigit()
:
x = [['+', '1', '0'], ['-', '2', '0']]
x = [[int(i) if i.isdigit() else i for i in j] for j in x]
Output:
[['+', 1, 0], ['-', 2, 0]]
If you want to a solution that works for signed integers as well:
x = [['+', '1', '0'], ['-', '-2', '0']]
def check_conversion(x):
try:
return int(x)
except:
return x
x = [list(map(check_conversion, i)) for i in x]
Output:
[['+', 1, 0], ['-', -2, 0]]
You're getting ValueError because '+'
and '-'
cannot be converted to a type int
. So you will need to check the type and/or contents of each string that you are looking to convert. The following example checks to see if each item in a sublist contains only digits 0-9:
listy = [['+', '1', '0'], ['-', '2', '0']]
T2 = [[int(x) if x.isdigit() else x for x in sublisty] for sublisty in listy]
print(T2)
>>> [['+', 1, 0], ['-', 2, 0]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With