我有一个清单:
var = ["renderPass1", "renderPass2","renderPass3", "renderPassFilter", "renderPassSets"]
如何只打印renderPass1,renederPass2等,我的意思是,只打印“renderPass”之后包含数字的成员
答案 0 :(得分:2)
使用正则表达式查找数字。
查看python库:Python: Re。你想看看“\ d”。
帮助我使用正则表达式的工具是Txt to Regex。您只需输入要匹配的字符串,然后使用GUI构建正则表达式。然后它会为你提供代码。
答案 1 :(得分:2)
for value in var:
if value[-1].isdigit(): # check if last char is a number
print value
现在,如果你想测试“renderPass”的字符串
for value in var:
if 'renderPass' in value and value[-1].isdigit()
print value
答案 2 :(得分:2)
我会给出两个答案,因为你的问题并不清楚什么是匹配。
如果数字的位置与不相关,则为此:
>>> var = ["renderPass1", "renderPass2","renderPass3", "renderPassFilter", "renderPassSets"]
>>> [x for x in var if any(c.isdigit() for c in x)]
['renderPass1', 'renderPass2', 'renderPass3']
>>>
这是因为如果数字必须在"renderPass"
之后:
>>> from re import search
>>> # I altered the values in here so I could demonstrate
>>> var = ["renderPass1", "renderPass2","renderPass3", "1renderPassFilter", "1renderPassSets"]
>>> [x for x in var if search("renderPass.*\d", x)]
['renderPass1', 'renderPass2', 'renderPass3']
>>>
答案 3 :(得分:2)
假设您只需要带有“SomeTextNumber”的模式,您可以这样写
[x for x in var if re.match("\w+\d$", x)]
答案 4 :(得分:1)
选择一个,具体取决于您对列表中的内容了解多少。
先打印3
print var[:3]
打印任何带有模式renderPass
后跟数字
print [name for name in var if name.startswith('renderPass') and name[9].isdigit()]
打印任何位置带有数字的任何名称
print [name for name in var if any(ch.isdigit() for ch in name)]
答案 5 :(得分:1)
for name in var:
try:
float(name[len("renderPass"):])
print name
except ValueError, er:
# does not have a number after renderPass -> do nothing
pass
答案 6 :(得分:1)
import re
p = re.compile("[0-9]$")
for s in var:
if p.search(s): print s