Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multiple condition IN string

Tags:

python

How to merge the condition in array format

lines = [line for line in open('text.txt')if 
        '|E|' in line and
        'GetPastPaymentInfo' in line and
        'CheckData' not in line and
        'UpdatePrintStatus' not in line
        ]

like

lines = [line for line in open('text.txt')if 
        ['|E|','GetPastPaymentInfo'] in line and
        ['CheckData','UpdatePrintStatus'] not in line]
like image 244
AlexLeung Avatar asked Jun 12 '15 08:06

AlexLeung


People also ask

How does Python handle multiple conditions at the same time?

Python has two logical operators for that. The and operator returns True when the condition on its left and the one on its right are both True. If one or both are False, then their combination is False too. That programs strict scenarios: only when several conditions are True at the same time will our if statement run. The or operator is different.

How to check multiple conditions in a single if statement in Python?

Note: For more information, refer to Decision Making in Python (if , if..else, Nested if, if-elif) Here we’ll study how can we check multiple conditions in a single if statement. This can be done by using ‘and’ or ‘or’ or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true.

What is a combined condition in Python?

This combination is True when two things happen at the same time: Either A or B is True. And C tests True. When A and B combine to False, and C is False, then the combined condition is False too. Now let’s consider some Python example programs to learn more.

How to use the if statement with strings in Python?

In Python, the if statement executes a block of code when a condition is met. It is usually used with the else keyword, which runs a block if the condition in the if statement is not met. This article will discuss the use of the if statement with strings in Python.


1 Answers

You can use a generator expression within all function to check the membership for all elements :

lines = [line for line in open('text.txt') if 
        all(i in line for i in ['|E|','GetPastPaymentInfo'])and
        all(j not in line for j in ['CheckData','UpdatePrintStatus'])]

Or if you want to check for words you can split the lines and use intersection method in set 1:

lines = [line for line in open('text.txt') if 
        {'|E|','GetPastPaymentInfo'}.intersection(line.split()) and not {'CheckData','UpdatePrintStatus'}.intersection(line.split())]

Note that you need to put your words within a set instead of list.


1) Note that since set object use hash-table for storing its elements and for returning the items as well, checking the membership has O(1) order and it's more efficient than list which has O(N) order.

like image 163
Mazdak Avatar answered Oct 08 '22 20:10

Mazdak