2

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
0

3 Answers 3

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 -")
Sign up to request clarification or add additional context in comments.

1 Comment

don't catch all exceptions! be specific: except IndexError.
1

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

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.