Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

How do I convert the negative int to an individual digit in the array? Something like this:

x = -3987

arr = [-3,9,8,7]

When I try to do this, I am getting an error.

ValueError: invalid literal for int() with base 10: '-'

x = [int(i) for i in str(x)]

1 Answer

0 votes
by (36.8k points)
edited by

Here is how I will be handling it.

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 the value of x was 3987

x = 3987

then the output will be:

[3,9,8,7]

 Want to gain end-to-end skills in Data Science with Python? Enroll today in this Data Science with Python Course and be a master in it

Browse Categories

...