【发布时间】:2015-02-25 15:01:17
【问题描述】:
我想编辑下面的代码以捕获所有以“_C[任意字母/任意数字/或无]”结尾的字符串
这是我的清单
name_list = ['chrome_PM',
'chrome_P',
'chromerocker_C',
'chromebike_P1',
'chromecar_CMale',
'chromeone_C1254',
'Lukate_Aids_Consumer_P']
for name in name_list:
counts_tail = re.compile('_C[\da-zA-Z_]*$')
if counts_tail.search(name):
print name
输出:
chromerocker_C
chromecar_CMale
chromeone_C1254
Lukate_Aids_Consumer_P
预期输出:
chromerocker_C
chromecar_CMale
chromeone_C1254
不应包含“Lukate_Aids_Consumer_P”,因为它不以“_C”结尾,我该如何编辑我的代码来处理这个错误?
谢谢
【问题讨论】:
-
一种pythonic方式:matching = [s for s in name_list if "_C" in s]
-
你用的是什么python?我在 python 2.7.6 中运行了你的脚本,输出只有这两个:
chromecar_CMalechromeone_C1254 -
我无法重现您的代码。我只用你当前的代码得到
chromecar_CMaleandchromeone_C1254。 -
奇怪,我用的是python 2.7
-
对不起,我使用的是旧的正则表达式,现在试试,它应该可以工作。