字符串切片不接受变量

问题描述 投票:0回答:1

我正在写一个简短的方法,以另一种方法根据逗号的索引对字符串进行切片。我将所有内容放入一个代码中以便于查看。

with open(testconfig) as f:
        lines=f.readlines()
        initlist=[]
        string_slice_list=[]
        b=0
        for line in lines:
            if "ML_STARConfig" in line:
                b+=1
                liste=sfind(line,",")
                liste.insert(0,0)
                input("line is {}sfind list of characters is {} and there should be a zero in position 0".format(line,liste))
                liste=list(reversed(liste))
                slices=[]
                for i in range(1,len(liste)):#make a list of tuples that have the beginning and end indexes of a "useful slice" of the string "line"
                    slices.append((liste[i-1],liste[i]))
                for item in slices:
                    b=item[0]
                    e=item[1]
                    word=line[b:e]
                    input("line is {} word indexes are {},{} and this should be a word ={}".format(line,b,e,word))

该方法从文件接受一行,并在该行中创建逗号索引的列表。我将每对索引分配给一个元组,并将每个元组附加到列表中。然后遍历元组列表以从该行中提取每个感兴趣的单词。除了当我传递元组列表中的数字时,它不会对字符串进行切片。并在最后一行不返回任何内容。这是我的堆栈跟踪或此代码...

line is ML_STARConfig, Master, C0RF, , rf, 7.1S B 2011-10-05, Firmware version
sfind list of characters is [0, 13, 21, 27, 29, 33, 52] and there should be a zero in position 0
line is ML_STARConfig, Master, C0RF, , rf, 7.1S B 2011-10-05, Firmware version
  word indexes are 52,33 and this should be a word =
line is ML_STARConfig, Master, C0RF, , rf, 7.1S B 2011-10-05, Firmware version
  word indexes are 33,29 and this should be a word =
line is ML_STARConfig, Master, C0RF, , rf, 7.1S B 2011-10-05, Firmware version
  word indexes are 29,27 and this should be a word =
line is ML_STARConfig, Master, C0RF, , rf, 7.1S B 2011-10-05, Firmware version
  word indexes are 27,21 and this should be a word =
line is ML_STARConfig, Master, C0RF, , rf, 7.1S B 2011-10-05, Firmware version
  word indexes are 21,13 and this should be a word =
line is ML_STARConfig, Master, C0RF, , rf, 7.1S B 2011-10-05, Firmware version
  word indexes are 13,0 and this should be a word =

该行的变量很明显起作用,并且开始和结束索引的变量在那里,但是line [#:#]命令只是神奇地停止工作并且非常令人沮丧。我不知道是什么原因造成的。我尝试列出逗号索引列表,但仍然无法正常工作。

我到底在这里想念什么?

python
1个回答
0
投票

我颠倒了切片的顺序,并固定了它。抱歉,我没有意识到我正在尝试反向执行切片,显然这不起作用。

澄清,如果您这样做

line[b:e]

和b> e,它不会给您带来很多好处。

© www.soinside.com 2019 - 2024. All rights reserved.