Python: 将 str 的一部分保存到数组中

Python: Saving parts of str to an array

我在 python 中遇到问题。我有一个变量集作为命令的输出,这个输出有很多行。为了简单起见,我们只是说这是命令的输出我有问题现在存储在变量 'OUTPUT':

FRU 0_2_3 机箱 1
FRU 0_2_4 机箱 1
FRU 0_2_5 机箱 1
FRU 0_2_6附件 1


现在我希望搜索该变量并仅存储显示#_ #_# 的那部分行。
注意:我不想为此使用文本文件

import re
disks=[]
i=0
OUTPUT=fbeclicommand("li -all") #This is the command on some exe that will gather the output and save it to this variable.
if re.search("\d{1,3}_\d{1,3}_\d{1,3}",OUTPUT):
    disks[i]=OUTPUT
    i+=1

我基本上只想在数组中存储数字部分,并为所有 4 个或有多少个数字都这样做

你可以用 space 拆分它并得到索引 1 处的数字。你也可以使用列表上的 .append 方法将它推送到数组而不是使用索引并将其设置为某个索引。同样的效果,更少的代码!

import re
disks=[]

OUTPUT = '''
FRU 0_2_3 enclosure 1
FRU 0_2_4 enclosure 1
FRU 0_2_5 enclosure 1
FRU 0_2_6 enclosure 1
'''
#OUTPUT=fbeclicommand("li -all") #This is the command on some exe that will gather the output and save it to this variable.
OUTPUTSplit= OUTPUT.split('\n')
for line in OUTPUTSplit:
    if re.search("\d{1,3}_\d{1,3}_\d{1,3}", line):
        disks.append(line.split(' ')[1])

print disks

输出

['0_2_3', '0_2_4', '0_2_5', '0_2_6']

我觉得如果您已经在使用正则表达式,您应该继续使用捕获组:

match = re.search("\d{1,3}_\d{1,3}_\d{1,3}", output_line):
if match is not None:
    disks.append(match.group())

https://docs.python.org/2/library/re.html