如果打印项不以给定的模式python结束,则打印项

时间:2014-04-30 10:10:06

标签: python regex string substring ends-with

我有一个清单:

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

我想打印所有不以下列模式结尾的项目:

'_C' or '_C%' (int) 

所以它可能类似于' _C'或者' _C1'或者' _C2939'

我的尝试:

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

你可以看到它不是很有活力,我怎么能接近这个?

2 个答案:

答案 0 :(得分:2)

您可以使用正则表达式:

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']

正则表达式解释:http://regex101.com/r/wG3zZ2#python

答案 1 :(得分:0)

你使用正则表达式:

import re

numeric_tail = re.compile('_C\d*$')

for item in mylist:
    if not numeric_tail.search(item):
        print item

模式匹配文字文本_C,后跟0位或更多位数,以$锚定在字符串末尾。

演示:

>>> 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