kitty
kitty

Reputation: 105

Find string in list and enter to if statement in python

Below is the list output

[[u'\x07\r\n', u'Error: command failed: Invalid IPspace name. The name n 
"yyy" is already in\r\n', u'       use by a cluster node, Vserver, or is 
the name of the local cluster.\r\n', u'\r\n'], [u'\x07\r\n', u'Error: command 
failed: The Vserver name is already used by another Vserver. \r\n', u'\r\n'], 
[u'\x07\r\n', u'Error: command failed: duplicate entry\r\n', u'\r\n']]

Below is the code:

    sub = "duplicate entry"
    if [s for s in self.error_check if sub in s]:
        self.pass_count += 1
    sub = "already exists"
    if [s for s in self.error_check if sub in s]:
        self.pass_count += 1
    sub = "Error:"
    if [s for s in self.error_check if sub in s]:
        self.pass_count += 1

In above code not working (Not entering to if statement that is not adding 1 to self.pass_count +)

What I am trying is, If list contains any keyword "Error:", "already exists" and "duplicate entry".

It should enter to if loop and add 1 to self.pass_count

Please help me on this

Tried below code as suggested by BoarGules

    if [s for s in self.error_check if "duplicate entry" in s]:
        self.pass_count += 1
        print "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    if [s for s in self.error_check if "already exists" in s]:
        print "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        self.pass_count += 1
    if [s for s in self.error_check if "Error:" in s]:
        self.pass_count += 1
        print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

Still not working

Upvotes: 0

Views: 349

Answers (2)

pramod
pramod

Reputation: 1493

def is_valid(self, sub):
    return any(s for ln in self.error_check for s in ln if sub in s)

if self.is_valid("duplicate entry"):
    self.pass_count += 1
if self.is_valid("already exists"):
    self.pass_count += 1
if self.is_valid("Error:"):
    self.pass_count += 1

Note: is_valid is a class method

Upvotes: 1

BoarGules
BoarGules

Reputation: 16952

self.error_check is a list of lists.

This test if [s for s in self.error_check if sub in s]: is checking if sub is an element of the list. What your code needs to check is if sub is a substring of an element of the list.

Unwind your list comprehension into a loop and put temporary print statements in to see what is going on.

Upvotes: 1

Related Questions