Python - 拆分函数 - 列表索引超出范围

标签 python split outofrangeexception

我正在尝试在 for 循环中获取子字符串。为此,我正在使用这个:

for peoject in subjects:
        peoject_name = peoject.content
        print(peoject_name, " : ", len(peoject_name), " : ",  len(peoject_name.split('-')[1]))

我有一些项目的句子中没有任何“-”。我该如何处理这个问题?

我遇到这个问题:

builtins.IndexError: list index out of range

最佳答案

for peoject in subjects:
    try:
        peoject_name = peoject.content
        print(peoject_name, " : ", len(peoject_name), " : ", len(peoject_name.split('-')[1]))
    except IndexError:
        print("this line doesn't have a -")

关于Python - 拆分函数 - 列表索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49876604/

相关文章:

python - 文本编辑器中类似 IPython 的代码完成

java - 如果分割字符是动态的或未知的,如何分割字符串?

c# - (C#) - 将 Split 之间的每个单词存储在一个数组中

r - 按 R 中的元素拆分字符向量?

asp.net - 从 Sql Server 2008 在 TreeView 中添加父节点和子节点

python - 如何从 api 响应中提取 application/zip?

python - Boto3:配置文件位置

python - 根据名称分割线

c++ - 错误 : Vector subscript out of range. 第 1201 行

允许有空格的 Java 列表