字符串比较在python中失败?

时间:2014-08-04 15:49:12

标签: python

我有一个小脚本,如下所示:

(注意比较)

def readVariations(path_to_source_config):
varsTuple = []
source_file = open(path_to_source_config, "r")

for line in source_file:
    line_no_spaces = line.replace(" ","")
    if line_no_spaces[0] == '[':
        current_line_ = line_no_spaces.replace("[", "") 
        current_line = current_line_.replace("]", "")
        section = "ExecutionOptimizer"
        if current_line == section:
            print current_line
    #_tuple = section_name, option_name, range_start, range_end, step
    #varsTuple.append(_tuple)
return varsTuple

它的作用是读取配置文件(.cfg)并需要检查它是否找到了特定的字符串。

配置文件中出现以下行:

[ExecutionOptimizer]

由于某种原因,当在文件中遇到相同的字符串时,比较失败。 你能告诉我为什么吗?

2 个答案:

答案 0 :(得分:5)

我怀疑line以换行符结尾,并且在所有replace操作中都会保留。然后您的比较失败,因为" ExecutionOptimizer \ n"不等于" ExecutionOptimizer"。您可以使用strip

来丢弃换行符
line_no_spaces = line.strip().replace(" ","")

答案 1 :(得分:-2)

使用"是"关键词。 " =="是用于平等测试

来自Python解释器:

> a = 'tea'
> b = ''.join(['t', 'e', 'a'])
> a == b
True
> a is b
False