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

2024-04-19 07:50:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我有一些项目在句子中没有“-”。我该怎么处理?在

我得到了这个问题:

^{pr2}$

Tags: 项目字符串nameinforlencontent句子
3条回答
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 -")

您只需检查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

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

或者选择split via[-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]

相关问题 更多 >