python - 字符串索引超出列表迭代范围

标签 python python-3.x

我对 python 相当陌生,我不确定如何修复超出范围的索引字符串。当我想将 mylist[i][0] 发送到格式化函数时,它发生在 while 循环之后。一般来说,任何关于我的代码的指针都会很棒!

    def formatting(str1):

if str1 == '?':
    return True
else:
    return False

while(i <= len(mylist)):
    val = formatting(mylist[i][0])
    if val == True:
        str1 = mylist[i]
        str2 = mylist[i+1]
        i = i + 2
        format_set(str1, str2)
    else:
        if format == True:
            if (margin + count + len(mylist[i])) <= width:
                if (i == (len(mylist)-1)):
                    list2.append(mylist[i])
                    print(" " * margin + " ".join(list2))   
                    break
            list2.append(mylist[i])
            count += len(mylist[i])
            i += 1                          
        else:
            print(" " * margin + " ".join(list2))
            list2 = []
            count = 0
    else:
        temp_margin = margin
        temp_width = width
        width = 60
        margin = 0
        if (margin + count + len(mylist[i])) <= width:
            if (i == (len(mylist)-1)):
                list2.append(mylist[i])
                print(" " * margin + " ".join(list2))
                margin = temp_margin
                width = temp_width
                break
            list2.append(mylist[i])
            count += len(mylist[i])
            i += 1                          
        else:
            print(" " * margin + " ".join(list2))
            list2 = []
            count = 0

最佳答案

改变

i <= len(mylist)

i < len(mylist)

关于python - 字符串索引超出列表迭代范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24421711/

相关文章:

python - 如何过滤列表中的元素并生成频率表

python - 如何 json 解析 python 输出并将其值存储在 dict 或变量中?

python - 如何仅将 swig 与已编译的 dll 和头文件一起使用

sql-server - 在 Python 中,如何构造 URL 来测试我的 SQL Server 实例是否正在运行?

Python 训练和测试错误

python-3.x - 分类数据的响应编码

python - 为什么 range 不返回数组,但是当我将它添加到列表时返回数组?

python - 使用python启动并行ssh渲染作业

python - 在 Centos 6.4 上安装 mysql-python

python - 求一个月内n个最大的平均值,但日期必须是唯一的(Pandas)