繁体   English   中英

无法比较python中的两个字符串

[英]Can´t compare two strings in python

我需要检查是否有函数调用,我知道它不是 txt 文件,但是当我读取一行并尝试使用 type() 打印时,它说 str 并让我正确打印所有文件,但无论出于何种原因无法比较这些行,我不知道为什么,当我编译时没有显示错误,文件的第一行是'#include <Arduino.h>'并且发现的 var 无论如何都是假的

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

尝试更换

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

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

strip() 函数删除行首和行尾的所有空格。

PS 尽量记住,在 Python 中,如果条件不需要在括号中并且行末尾不需要分号。 否则每个人都会知道你是一个真正的 C 程序员。

如果更改行,最后一个字符是\\n

所以这可能对你有用:-

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

比较字符串时应该小心。 在这种情况下,导致此问题的空白字符。 有很多无法看到但可能存在的空白字符。 因此,处理此类文件时的一个好习惯是删除这些空白字符。 您可以使用strip()从字符串的两端删除空白字符。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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