How to extract row with certain worlds from a result that contains multiple lines

Viewed 47

Trying to find row with Device is ready string from response_without_empty_lines that contains multiple lines:

lines = decoded_bytes.split("\n")
    non_empty_lines = [line for line in lines if line.strip() != ""]
    response_without_empty_lines = ""
    for line in non_empty_lines:
        response_without_empty_lines += line + "\n"

here i got only lines that contain data, next I want to find a line containing Device is ready:

for i in response_without_empty_lines:
    if 'Device is ready' in i:
        print(i)

... and get nothing. where am i wrong?

4 Answers

you can use i.find("Device is ready") > 0, find returns a positive number(the index of the first encounter of the parameter) if found, or -1 otherwise

Just make the response_without_empty_lines = [] then in the for loop:

response_without_empty_lines.append(line)
decoded_bytes = "Device is ready haha\nAnother phrase"

lines = decoded_bytes.split("\n")
non_empty_lines = [line for line in lines if line.strip() != ""]
response_without_empty_lines = ""

for line in non_empty_lines:
    response_without_empty_lines += line + "\n"

for i in non_empty_lines:
    if i.find("Device is ready") >= 0:
        print(i)

my bad, it was =>

Instead of checking if the line is not empty, you can check if the line contains Device is ready.

Then the for comprehension will give a list of lines that contain that sub string.

decoded_bytes = ("This is a test\n\n"
                            "Where the Device is ready\n"
                            "test 1\n"
                            "test 2\n"
                            "Device is ready")
non_empty_lines = [line for line in decoded_bytes.split("\n") if "Device is ready" in line]
print(non_empty_lines)

Output

['Where the Device is ready', 'Device is ready']

Python demo

Related