繁体   English   中英

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

[英]Python - Split Function - list index out of range

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

您有几个选项,具体取决于您在没有连字符的情况下要执行的操作。

通过[-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]

你可以检查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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM