Python - 拆分函数 - 列表索引超出范围
Python - Split Function - list index out of range
我正在尝试在 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
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 -")
您有几个选项,具体取决于您在没有连字符的情况下要执行的操作。
select 通过 [-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]
你可以检查 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
我正在尝试在 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
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 -")
您有几个选项,具体取决于您在没有连字符的情况下要执行的操作。
select 通过 [-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]
你可以检查 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