【问题标题】:Python - Split Function - list index out of rangePython - 拆分函数 - 列表索引超出范围
【发布时间】:2018-04-17 11:13:51
【问题描述】:

我正在尝试在 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

【问题讨论】:

    标签: python split outofrangeexception


    【解决方案1】:
    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 -")
    

    【讨论】:

    • 不要捕获所有异常!具体:except IndexError.
    【解决方案2】:

    你可以检查peoject_name中是否有'-'

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

    【讨论】:

      【解决方案3】:

      您有几个选项,具体取决于您在没有连字符的情况下要做什么。

      要么通过[-1] 从拆分中选择最后一项,要么使用三元语句应用替代逻辑。

      x = 'hello-test'
      print(x.split('-')[1])   # test
      print(x.split('-')[-1])  # test
      
      y = 'hello'
      print(y.split('-')[-1])                                 # hello
      print(y.split('-')[1] if len(y.split('-'))>=2 else y)   # hello
      print(y.split('-')[1] if len(y.split('-'))>=2 else '')  # [empty string]
      

      【讨论】:

        猜你喜欢
        • 2013-05-31
        • 1970-01-01
        • 2017-10-24
        • 2021-11-29
        • 1970-01-01
        • 1970-01-01
        • 2022-11-01
        • 2015-10-09
        • 1970-01-01
        相关资源
        最近更新 更多