Does Python offer something like Perl's "unless"?

Question:

I have some code like:

if '@' in line and line == l:
    lineMatch = True
    line = line.strip('n')
    line = line.split('@')[1]
    line = line + '<br>n'
    labels.append(line)

I do not want to append a line to a label if it has p4port in it. Is there something like unless in Python, that would allow me to write something like labels.append(line) unless 'p4port' in line?

Asked By: user1795998

||

Answers:

What about ‘not in’?:

if 'p4port' not in line:
    labels.append(line)

Also i guess that you code can be modified then to:

if '@' in line and line == l and 'p4port' not in line:
    lineMatch = True
    labels.append(line.strip('n').split('@')[1] + '<br>n')
Answered By: Artsiom Rudzenka

There’s no “unless” statement, but you can always write:

if not some_condition:
    # do something

There’s also the not in operator as Artsiom mentioned – so for your code, you’d write:

if '@' in line and line == l:
    lineMatch = True
    line = line.strip('n')
    line = line.split('@')[1]
    line = line + '<br>n'
    if 'p4port' not in line:
        labels.append(line)

… but Artsiom’s version is better, unless you plan to do something with your modified line variable later.

Answered By: Zero Piraeus

The error you’re getting in your (rather drastically) edited question is telling you that the variable lineMatch doesn’t exist – which means the conditions you specified for setting it weren’t met. It might help to add a line like LineMatch = False as the first line inside your outer for loop (before the first if statement), to ensure that it does exist.

Answered By: Zero Piraeus
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.