简体   繁体   中英

Python - Split Function - list index out of range

I'm trying to get a substring in a for loop. For that I'm using this:

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

I have some projects that don't have any "-" in the sentence. How can I deal with this?

I'm getting this issue:

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 -")

You have a few options, depending on what you want to do in the case where there is no hyphen.

Either select the last item from the split via [-1] , or use a ternary statement to apply alternative logic.

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]

you could just check if there is a '-' in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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