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
SaCvP
  • 393
  • 2
  • 4
  • 16

3 Answers3

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 -")
marc
  • 914
  • 6
  • 18
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]
jpp
  • 159,742
  • 34
  • 281
  • 339
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
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111