Home > OS >  python for loop isnt recognising int inside a list
python for loop isnt recognising int inside a list

Time:12-17

I am trying to change the contents of a list changing every -127 for a 1 and -128 for a 0. However I struggle to find why my code does not change the digits as intended or even recognizes them:

my_file = open("log.txt", "r")
content = my_file.read()
my_file.close()

clean_contnet = content.split("\n")


for idx, x in enumerate(clean_contnet):

     if x == -127 or x == -128:
        if x == -127:
            clean_contnet[idx] = 1

        else:
            clean_contnet[idx] = 0

     else:
        print("no -127 or -128 detected")

print(clean_contnet)

The (shortened) contents of 'log.txt' are as follows

0
-127
1
-128
0
-127
1
-128
0
-127
1

CodePudding user response:

clean_contnet is a list of strings, not ints. You should do x = int(x) before checking its value.

CodePudding user response:

You never convert your read in string data into integers - comparing a string with a number never will lead to a True statement.

Change:

# convert read in numbers to string - will crash if non numbers inside
clean_content = [int(part) for part in content.split("\n") if part]

or compare vs string:

if x in ("-127","-128"):
    clean_content[idx] = 1 if x == "-127" else 0

This uses a ternary expression - see Does Python have a ternary conditional operator?

  • Related