0

I want to match multiple strings from a file. How do I do this in python ?

Objective: match the lines which is having both values of "DC1" & "TIER2" from file


My code but give matches any string from strings object

strings = ["DC1","TIER2"]
with open(r"D:\kick-6.log", "r" ) as data:
    for deltaa in data:
        deltaa = data.readline().rstrip()
        print ("*********")
        for item in strings:
            if item in deltaa:
                print (deltaa)
3
  • You'd post the contents of kick-6.log. Commented Jan 4, 2016 at 7:22
  • 1
    You probably just want deltaa = deltaa.rstrip() on the fourth line. Commented Jan 4, 2016 at 7:25
  • Yes . tried and it's fine Commented Jan 4, 2016 at 7:27

1 Answer 1

2

Use all for your checking:

all(iterable) Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
strings = ["DC1","TIER2"]
with open(r"D:\kick-6.log", "r" ) as data:
    for deltaa in data:
        if all(x in deltaa for x in strings): #Check if all items in strings exit in deltaa
            print (deltaa)

And if you want to check if at least one of strings is in deltaa use any instead:

any(iterable) Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
strings = ["DC1","TIER2"]
with open(r"D:\kick-6.log", "r" ) as data:
    for deltaa in data:
        if any(x in deltaa for x in strings): #Check if any item in strings exits in deltaa
            print (deltaa)
Sign up to request clarification or add additional context in comments.

3 Comments

@veejay .. Feel free to accept my answer
if i want to print only non matched strings from the above example what to do?
@veejay...you mean printing lines from file that do not match with strings ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.