Python: "or" in short form

Asked by At

Is there a possibility to write this in a shorter way?

elif line.startswith('\tVLRLIST=') and (line.rstrip()[9:-1] == '27' or line.rstrip()[9:-1] == '28' or line.rstrip()[9:-1] == '29')

3 Answers

BlueSheepToken On

As a general case, you can use the in keyword,

elif line.startswith('\tVLRLIST=') and line.rstrip()[9:-1] in ('27', '28', '29'):

For this specific example, all of them are contained in a range:

elif line.startswith('\tVLRLIST=') and (int(line.rstrip()[9:-1]) in range(27, 30):
Amadan On
elif re.match(r'^\tVLRLIST=2[7-9]\s*$', line):
Rafael On

I would use a different approach and try to name these, it's much more readable.

def prefix_is_correct(line):
    return line.startswith('\tVLRLIST=')

def is_valid(line):
    return prefix_is_correct(line) and line.rstrip()[9:-1] is in ['27', '28', '29']


elif is_valid(line):