根据字符串中的某些数字将一个字符串转换为字符串列表

2024-04-25 08:05:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,需要找到一种将数字信号格式化为文本格式的方法。具体地说,我需要将字符串从原来的转换为下面列出的新字符串。希望有人能帮忙!你知道吗

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

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

非常感谢。你知道吗


Tags: 方法文本格式字符串newstringoldlistclock
3条回答

另一种方法是使用Python自己的解析器来处理字符串,因此如果字符串是duff,它将引发SyntaxError。它可能不像regex或spliting那么容易理解,但却是一个合理的选择——特别是如果您发现您正在做更多的这类工作(或者看看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]']

下面的代码可以满足您的要求,结合使用正则表达式、拆分和列表理解:

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

您可以使用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]']

相关问题 更多 >