How can I avoid IndexError: list index out of range when the range can be random amount of splits, using Python 3?

How can I avoid IndexError: list index out of range when the range can be random amount of splits, using Python 3?

假设我有一个拆分字符串,最多可以包含 x 个单词,并且该拆分集随机变化。 (我在这个例子中使用了 3。)如果在任何时候我必须检索第三个单词并且第三个单词不存在,我该如何避免“IndexError:列表索引超出范围”。 3 个字符串 wordOne、wordTwo 和 wordThree 必须存在以备后用。

userInput = input('Type up to 3 words : ')
userInputSplit = userInput.split()

wordOne = userInputSplit[0]
if userInputSplit[1] != None:
    wordTwo = userInputSplit[1]
if userInputSplit[2] != None:
    wordThree = userInputSplit[2]


print(wordOne + ' ' + wordTwo + ' ' + wordThree)

您可以检查userInputSplit的长度:

userInput = input('Type up to 3 words : ')
userInputSplit = userInput.split()

wordOne = userInputSplit[0]
if len(userInputSplit) == 1:
    wordTwo = 'None'
    wordThree = 'None'
elif len(userInputSplit) == 2:
    wordTwo = userInputSplit[1]      
    wordThree = 'None'
else:
    wordTwo = userInputSplit[1]      
    wordThree = userInputSplit[2]    

上面的代码可以写成两行:

wordTwo = userInputSplit[1] if len(userInputSplit])>1 else 'None'
wordThree = userInputSplit[2] if len(userInputSplit])>2 else 'None'

你也可以使用 try-except:

try:
    wordTwo = userInputSplit[1]
except IndexError: 
    wordTwo = 'None'
try:
    wordThree = userInputSplit[2]
except IndexError: 
    wordThree = 'None'