hekuma
hekuma

Reputation: 43

Extracting items from 2d List

I have one 2d list splited_body:

splited_body= [
 ['startmsg', 'This is a test massage.', 'endmsg\r\n'], 
 ['startmsg', 'Hi There is some issue in the process.', '5', 'F3', 'D1', '2', 'endmsg\r\n']
]

I want to print all data before 'endmsg' and I am using for and if combination as below:

for i in range(len(splited_body)):
    for j in range(len(splited_body[i])):
        if splited_body[i][j] == 'endmsg':
            break
        x = splited_body[i][j]
        print(x)

But it is printing all items in the list. How can I do that. Please someone tell what I am doing wrong?

Upvotes: 3

Views: 96

Answers (3)

HuyDang
HuyDang

Reputation: 1

Python removes last element from list by [:-1].

for items in splited_body:
    print(items[:-1])

Upvotes: 0

AboAmmar
AboAmmar

Reputation: 5559

I'd use startswith:

for b in splited_body:
    for i in b:
        if i.startswith('endmsg\r\n'):
            break
        print(i)

Upvotes: 1

Avinash
Avinash

Reputation: 875

Using in keyword you can iterate individual elements in a list. So you can try this out:

for body in splited_body:
    for msg in body:
        if msg.strip() == 'endmsg':
            break
        print(msg)

Upvotes: 2

Related Questions