0

我是 python 新手,需要找到一种方法以文本格式格式化我的数字信号。具体来说,我需要将字符串从 string_old 转换为 list_new 下面。希望有人可以在这里提供帮助!

string_old = 'clock[5,4,1,0]'

list_new = ['clock[5]','clock[4]','clock[1]','clock[0]']

非常感谢。

4

3 回答 3

3

您可以使用regex和列表理解:

>>> 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]']
于 2013-05-03T19:04:20.303 回答
0

一种使用 Python 自己的解析器来处理字符串的替代方法 - 所以SyntaxError如果它是 duff 它将引发。它可能不像正则表达式或拆分那样容易理解,但它是一个合理的选择 - 特别是如果你发现你正在做更多这样的事情(或者看看pyparsing哪个可以处理这些类型的输入):

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]']
于 2013-05-03T21:39:58.020 回答
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
于 2013-05-03T19:06:55.307 回答