0

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)]
2
  • 3
    The only time you will have a negative number is for the left most digit, I would handle that case seperately and simply change your list comprehension to arr = [int(i) for i in str(x)[1:] Then you can have a conditional which checks the original number and changes the arr[0] if its negative. Commented Nov 10, 2020 at 4:38
  • Remark above is correct, but has a typo, you should use arr = [int(i) for i in str(x)[1:]] Commented Nov 10, 2020 at 6:31

3 Answers 3

1

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

0

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)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.