-2

i am trying to check and print if following list contains specific string or substring using Python,

This is my input

[
  [
    "SessionTimeOut: Request reach to it's max time. {'VwasKXznXVVzYU6iAAAB': None} were registered but ['192.168.2.2', '192.168.2.3'] were expected."
  ],
  [
    "CommonException: element with 'id' was not found"
  ],
  [
    "JenkisException: Element missing because service was down"
  ]
]

Now i want to get the output string if it contains

"SessionTimeOut: Request reach to it's max time.

I am able to check it this way

print('SessionTimeOut: Request reach to it's max time.' in str(response['data']))

It returns True but i also want that complete string I am able to print that as response['data'][0][0] this is not a good idea.

I want to printout the complete string dynamically which contains that text, How can i achieve this. Thank you.

Zain
  • 49
  • 6

1 Answers1

1

How about using any built-in and itertools.chain:

from itertools import chain

data = [
    [
        "SessionTimeOut: Request reach to it's max time. {'VwasKXznXVVzYU6iAAAB': None} were registered but ['192.168.2.2', '192.168.2.3'] were expected."
    ],
    [
        "CommonException: element with 'id' was not found"
    ],
    [
        "JenkisException: Element missing because service was down"
    ]
]

string_to_search = "SessionTimeOut: Request reach to it's max time."
print(any(string_to_search in obj for obj in chain(*data)))

If you want to return that specific string:

print([obj for obj in chain(*data) if string_to_search in obj][0])

Ouptut:

True
funnydman
  • 9,083
  • 4
  • 40
  • 55
  • Yes this is returning true, May be my question was not clear i want to print that specific string which contains string to search text. I am already getting true or false using this `'print(''SessionTimeOut: Request reach to it's max time.'' in str(response['data']))` but i want to print out that specific string which contains this. – Zain Aug 10 '22 at 10:56
  • @Zain I've updated the answer, can you check? – funnydman Aug 10 '22 at 11:00
  • Yes that's working fine,Thank you. I just want to know that can't i do with the approach i used in my question? – Zain Aug 10 '22 at 11:05
  • @Zain, at least you need to iterate over all lists in data and check string occurrence. – funnydman Aug 10 '22 at 11:08
  • Here we again giving the index `[0]` which is not will work if the index is different. – Zain Aug 10 '22 at 12:13
  • The solution i wrote in my question is also giving me the results if i give index, So looking for something dynamic. @funnydman – Zain Aug 10 '22 at 12:14
  • @Zain what do you mean by more dynamic? – funnydman Aug 10 '22 at 14:20