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

正規表現、分割、およびリスト内包表記の組み合わせを使用して、あなたが求めることを行うコードを次に示します。

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 に答える