Search code examples
pythonregexstringsubstringends-with

print item if it does not ends with a given pattern python


I have a list:

mylist = ['summer_C','summer_C1','summer_P','summer_C123','summer_p32']

I want to print all items which do not end with the following pattern:

'_C' or '_C%' (int) 

so it could be something like '_C' or '_C1' or '_C2939'

My attempt:

for item in mylist:
    if item[-2:] != '_C' or item[-x:] != '_C(INT)'
        print item

As you can see its not very dynamic, how can I approach this?


Solution

  • You'd use a regular expression:

    import re
    
    numeric_tail = re.compile('_C\d*$')
    
    for item in mylist:
        if not numeric_tail.search(item):
            print item
    

    The pattern matches the literal text _C, followed by 0 or more digits, anchored at the end of the string by $.

    Demo:

    >>> import re
    >>> numeric_tail = re.compile('_C\d*$')
    >>> mylist = ['summer_C','summer_C1','summer_P','summer_C123','summer_p32']
    >>> for item in mylist:
    ...     if not numeric_tail.search(item):
    ...         print item
    ... 
    summer_P
    summer_p32