Search code examples
pythonarraysnegative-numberformatted

python suppress minus charactere


On Python3, I have ome data on array:

tst_val:  ['', '1', '--2147483648-0', '', 0]    => bad values
tst_val:  ['1', '0', '0']                       => values OK
tst_val:  ['0', '0', '1']                       => values OK
tst_val:  ['1', '-0', '-1']                     => bad values

Then tabVal_sub = str(tst_val).split(' ')

In my sub_val, I only want values, properly formatted, like 0 or 1 (int format preferred). If value is not '1' or '0', replace by default with '0'.

I tried to make a:

for k in range(1, 4):
#    print ('Check tabVal_sub ' + str(k))
    l = [0, 1]
    if int(tabVal_sub[k]) not in l:
        tabVal_sub[k] = 0

But, it's crashing ! (go out of try catch)

Please, do you have an idea to fix it?

Thx ;o)


Solution

  • If your problem truly is

    In my sub_val, I only want values, properly formatted, like 0 or 1 (int format preferred). If value is not '1' or '0', replace by default with '0'.

    then the solution is simply

    sub_val = [(int(val) if val in ("1", "0") else 0) for val in tst_val]