Search code examples
pythonpython-2.7python-3.xfor-loopfilter

One line python code to remove all the strings that doesn't start with T or t and if they contain number greater then 6


Eg:

List=["tata1","tata2","Tata3","mdkjd","djhdj","Tata8","t9","t2"]

Output should be:["tata1","tata2","Tata3","t2"]

I tried :

content = [item for item in List if terminal.lower().startswith('t')]

My doubt if I can append one more condition with the if I used in my code?

If yes, how?

I tried writing but it gives error.


Solution

  • You can use and to test multiple conditions.

    >>> [i for i in l if i and i[0] in 'tT' and all(j not in i for j in '789')]
    ['tata1', 'tata2', 'Tata3', 't2']
    

    So from left to right this will test:

    • non empty string
    • starts with 't' or 'T'
    • has any of the digits '7', '8', or '9'

    These conditions will "short circuit" meaning upon the first test failing, there is no need to check the following conditions as False and (anything) is always False.