简体   繁体   中英

Negative number to a string. Python

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

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]

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM