2

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Boosted_d16
  • 13,340
  • 35
  • 98
  • 158

2 Answers2

2

You can use regex for this:

import re

r = re.compile(r'_C\d+$')
mylist = ['summer_C','summer_C1','summer_P','summer_C123','summer_p32']
print [x for x in mylist if not r.search(x)]
#['summer_C', 'summer_P', 'summer_p32']

Regex explanation: http://regex101.com/r/wG3zZ2#python

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343