我正在尝试在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
答案 0 :(得分: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 -")
答案 1 :(得分:0)
您有几个选项,具体取决于您在没有连字符的情况下的操作。
通过[-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]
答案 2 :(得分:0)
您只需检查'-'
中是否有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