![](/img/trans.png)
[英]IndexError: list index out of range error for python split function
[英]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 -")
您有幾個選項,具體取決於您在沒有連字符的情況下要執行的操作。
通過[-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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.