Reputation:
How do I convert a negative int to individual digit in an array? Something like this...
x = -3987
arr = [-3,9,8,7]
I tried to do this but I got an error.
ValueError: invalid literal for int() with base 10: '-'
x = [int(i) for i in str(x)]
Upvotes: 0
Views: 522
Reputation: 878
Try this,
input_number = +223
res_digits = list(str(input_number))
if res_digits[0] == '-':
res_digits[0] = res_digits[0] + res_digits[1]
res_digits.pop(1)
elif res_digits[0] == '+':
res_digits.pop(0)
print(list(map(int, res_digits)))
Upvotes: 0
Reputation: 11342
List comprehension works here
x = -3987
xs = str(x)
lst = [int(d) for d in (([xs[:2]]+list(xs[2:])) if xs[0]=='-' else xs)]
print(lst)
Output
[-3, 9, 8, 7]
Upvotes: 0
Reputation: 8508
Here's how I will handle it. The answer was already provided by @Fuledbyramen.
x = -3987
#arr = [-3,9,8,7]
if x < 0:
arr = [int(i) for i in str(x)[1:]]
arr[0] *= -1
else:
arr = [int(i) for i in str(x)]
print (arr)
The output of this will be:
[-3,9,8,7]
If value of x was 3987
x = 3987
then the output will be:
[3,9,8,7]
Upvotes: 1