检查文件中的行是否在Python中包含大写字母

时间:2018-07-13 17:04:55

标签: python char

我正在逐行读取文件,并且说我不在乎“如果”,则文件的这一行包含大写字母。因为如果要,我想使用它。如果不想的话,我不想使用文件的这一行。

我可以仅使用if语句吗?还是我必须使用for循环。我已经有两个嵌套的语句。

我的代码:

with open(var) as config_file: #open file
for line in config_file: #line by line reading of file
    #if "description" and capital letter is contain in line:
        line = line.replace('\n' , '').replace('"' , '').replace(']' , '') #removes all extra characters
        i = "| except " + (line.split("description ", 1)[1]) + " " #split the line and save last index (cust name)
        cus_str+=i #append to string
config_file.close()

3 个答案:

答案 0 :(得分:5)

是的。内置的any函数使此操作变得简单:

with open(filename) as f:
    for line in f:
        if any(letter.isupper() for letter in line):
            print(line)

答案 1 :(得分:1)

使用正则表达式可能会过分,但这非常简单:

import re
if re.search('[A-Z]', line):

答案 2 :(得分:-1)

[]byte{0xFF, 0x00, 0x00, 0x00, 0x04, 0xD4, 0x50, 0x01, 0x00}

with open(var) as config_file : data = [i.strip() for i in config_file.readlines() if any(j != j.lower() for j in i)] 仅包含大写字符的字符串。