Python-拆分函数-列表索引超出范围
我试图在for循环中得到一个子字符串。为此,我使用以下方法:Python-拆分函数-列表索引超出范围,python,split,outofrangeexception,Python,Split,Outofrangeexception,我试图在for循环中得到一个子字符串。为此,我使用以下方法: for peoject in subjects: peoject_name = peoject.content print(peoject_name, " : ", len(peoject_name), " : ", len(peoject_name.split('-')[1])) 我有一些项目在句子中没有任何“-”。我该怎么处理 我得到了这个问题: builtins.IndexError: lis
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
您有几个选项,这取决于在没有连字符的情况下要执行的操作 通过
[-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]
您只需检查
项目名称中是否有'-'
:
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
不要捕捉所有异常!具体点:索引器除外
。
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