简体   繁体   中英

Python3 For-Loop and If-Statement trouble

I just wrote some code which should go through each line of a file and should call another function if the number after the first word of the line is a 1.

The file looks like this:
Button0 1
Button1 0
Motion 0
Order 0

My code:

currLog = open(log,"r") #Open current Log-File
    for line in currLog:    #Loop through each Line
        pos = line.split(" ")   #Split line into Name(pos0) and Answer(pos1)
        print(pos[1])
        if (pos[1] == "0"):
            print("Button0")

Shell-Ouput:

1

0

0

0

Button0

Like you see it only enters the if-statement at the last line

Already thankful for help.

You have a new line character that you need to account for. If you print the entire pos variable, you will see the following output:

['Button0', '1\n']
['Button1', '0\n']
['Motion', '0\n']
['Order', '0']

Your solution would either be to account for the new line character (remove it prior to splitting on " ") or use the .split() string function. Using split() without a separator will also account for consecutive, and trailing whitespace characters. The Python docs explain it very well.

str.split(sep=None, maxsplit=-1) Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].

For example:

'1,2,3'.split(',') ['1', '2', '3'] '1,2,3'.split(',', maxsplit=1) ['1', '2,3'] '1,2,,3,'.split(',') ['1', '2', '', '3', '']

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

For example:

'1 2 3'.split() ['1', '2', '3'] '1 2 3'.split(maxsplit=1) ['1', '2 3'] ' 1 2 3 '.split() ['1', '2', '3']

It looks like it is getting the end of line character in the second string as well. From the output it seems that it is printing "1\\n\\n" effectively. Python's print statement automatically adds one return, so the string it is printing must contain the other one.

I'm seeing two easy solutions to your problem:

if (not int(pos[1]))

This option parses the input string into just the integer and as Python interprets anything that isn't '0', 'NULL' or "" as false we can invert it and get a true value for 0.

if (pos[1][0] == "0")

Since the string your comparing has the return character at the end it isn't equal to 0. If you just grab the first character of the string you should be able to get just the "0" and be able to compare it the way you're wanting.

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