Home > database >  Print elements containing only 2 strings
Print elements containing only 2 strings

Time:09-25

I have this list

lst = [' SOME TEXT\nSOME TEXT\nFTY = 1', 'A|1\nB|5\nC|3\n \nD|0\nE|0', 'D|4\nE|1\nG|1', '\nblah blah', '\n---    HHGTY', 
    'SOME TEXT\nFTY = 1\nA|3\nB|2\nC|8\nD|6\nE|9\nF|3', '', 'blah blah\n \nblah blah', 
    '---    HHGTY'
    ]

and I want to print only the elements containing | or HHGTY. I using the code below, but is printing SOME TEXT and FTY = 1 too. What is wrong? Thanks

>>> for s in lst:
...     if ("|" in s) or ("HHGTY" in s):
...             print(s)
...
A|1
B|5
C|3

D|0
E|0
D|4
E|1
G|1

---    HHGTY
SOME TEXT
FTY = 1
A|3
B|2
C|8
D|6
E|9
F|3
---    HHGTY
>>>

CodePudding user response:

I think what you want is:

for s in lst:
    for subs in s.split('\n'):
        if ("|" in subs) or ("HHGTY" in subs):
            print(subs)

CodePudding user response:

Your code is doing everything right: SOME TEXT and FTY = 1 are parts of SOME TEXT \ nFTY = 1 \ nA | 3 \ nB | 2 \ nC | 8 \ nD | 6 \ nE | 9 \ nF | 3.

CodePudding user response:

Because in your 'SOME TEXT\nFTY = 1\nA|3\nB|2\nC|8\nD|6\nE|9\nF|3' element '|' is present.

CodePudding user response:

If you are looking for words:

lst = [' SOME TEXT\nSOME TEXT\nFTY = 1', 'A|1\nB|5\nC|3\n \nD|0\nE|0', 'D|4\nE|1\nG|1', '\nblah blah', '\n---    HHGTY', 
    'SOME TEXT\nFTY = 1\nA|3\nB|2\nC|8\nD|6\nE|9\nF|3', '', 'blah blah\n \nblah blah', 
    '---    HHGTY'
    ]

for s in lst:
    for j in s.split():
        if ("|" in j) or ("HHGTY" in j):
            print(j)

Just split each entry in the list and then check.

Output:

A|1
B|5
C|3
D|0
E|0
D|4
E|1
G|1
HHGTY
A|3
B|2
C|8
D|6
E|9
F|3
HHGTY
  • Related