import ast
s = 'clock[5,4,1,0]'
slc = ast.parse(s).body[0].value
print ['{}[{}]'.format(slc.value.id, el.n) for el in slc.slice.value.elts]
# ['clock[5]', 'clock[4]', 'clock[1]', 'clock[0]']
import re
string_old = 'clock[5,4,1,0]'
match = re.search('(.*)\[(.*)\]', string_old)
if match:
indices = match.group(2).split(',')
list_new = ['{0}[{1}]'.format(match.group(1), ind) for ind in indices]
print list_new
>>> import re
>>> strs='clock[5,4,1,0]'
>>> nums = re.findall("\d+",strs) #find all the numbers in string
>>> word = re.search("\w+",strs).group() #find the word in the string
#now iterate over the numbers and use string formatting to get the required output.
>>> [ "{0}[{1}]".format(word,x) for x in nums]
['clock[5]', 'clock[4]', 'clock[1]', 'clock[0]']
另一种方法是使用Python自己的解析器来处理字符串,因此如果字符串是duff,它将引发
SyntaxError
。它可能不像regex或spliting那么容易理解,但却是一个合理的选择——特别是如果您发现您正在做更多的这类工作(或者看看pyparsing
,它可以处理这些类型的输入):下面的代码可以满足您的要求,结合使用正则表达式、拆分和列表理解:
您可以使用
regex
和列表理解:相关问题 更多 >
编程相关推荐