Skip to main content
 首页 » 编程设计

python之如何在不使用正则表达式的情况下不区分大小写地搜索字符串

2025年05月04日29lori

我想在文件中搜索包含给定字符串但不匹配大小写的所有行。如何使此代码不区分大小写?

with open(logfile) as inf: 
    for line in inf: 
        if var in line: 
            print 'found',line 

请您参考如下方法:

with open(logfile) as fin: 
    for line in fin: 
        if var.lower() in line.lower():  # makes this case insensitive 
            print 'found', line.rstrip() # You will be printing double new lines  
                                         #  without rstrip here