Home > Mobile >  Can´t compare two strings in python
Can´t compare two strings in python

Time:11-05

I need to check if thre is a call for a function, I know it's not a txt file but when I read a line and try to print using type() it's says str and let me to print all the file correctly but for whatever reason the lines can't be compare and I don't know why, when I compile shows no error, the first line of the file is '#include <Arduino.h>' and the var found is false anyways

import os
def BeforeBuild():
    found = False
    with open(r"\src\OTAWEBAP.cpp", "r") as f:
        for line in f:
            print (line)
            if(line == '#include <Arduino.h>'):
                found = True;
        if(not found):
            raise Exception("OtaIni function not found, you need to use it to preserve OTA functions in your new deploy")
        else:
            print('function OtaIni was found')
    f.close()
BeforeBuild()

CodePudding user response:

Try replacing

if(line == '#include <Arduino.h>'):
            found = True;

with

if line.strip() == '#include <Arduino.h>':
    found = True

The strip() function removes ALL whitespace at the beginning and end of the line.

P. S. Try to remember that in Python, if conditions don't need to be in parenthesis and lines don't need semicolons at the end. Otherwise everyone will know that you're really a C programmer at heart.

CodePudding user response:

The last character is \n if you change the line.

So this may work for you:-

import os
def BeforeBuild():
    found = False
    with open(r"\src\OTAWEBAP.cpp", "r") as f:
        for line in f:
            print (line)
            if(line[:-1] == '#include <Arduino.h>'):
                found = True;
        if(not found):
            raise Exception("OtaIni function not found, you need to use it to preserve OTA functions in your new deploy")
        else:
            print('function OtaIni was found')
    f.close()
BeforeBuild()

CodePudding user response:

Caution should be taken while comparing strings. In this case a whitespace character causing this issue. There are a lot of whitespace characters that could not be seen but may present. So, a good practice while working with this kind of files is to remove these whitespace characters. You can use strip() to remove whitespace characters from both end of a string.

import os
def BeforeBuild():
    found = False
    with open(r"\src\OTAWEBAP.cpp", "r") as f:
        for line in f:
            line = line.strip();
            print (line)
            if line == '#include <Arduino.h>':
                found = True;
        if not found:
            raise Exception("OtaIni function not found, you need to use it to preserve OTA functions in your new deploy")
        else:
            print('function OtaIni was found')
    f.close()
BeforeBuild()
  • Related