rexillion
rexillion

Reputation: 11

How do I use the var.split

if inp.startswith("add "):
    print(((inp.split('d ')[1]).split(', ')[0]) + ((inp.split(' ')[1]).split(', ')[1]))

I am getting the error message that the list index is out of range what do i do

code to replicate the error:

inp = "add 12, 12"
if inp.startswith("add "):
   print(((inp.split('d ')[1]).split(', ')[0]) + ((inp.split(' ')[1]).split(', ')[1]))

Upvotes: 1

Views: 180

Answers (2)

Chris Maes
Chris Maes

Reputation: 37782

.split(', ')[1]

you are resting here on the fact that split gives you (at least) two elements. Suppose that your input string does not contain a ,, then you are trying to fetch the second entry from a list that contains only one element --> index out of range error.

Globally your use of split is ok, but you need to make sure that such errors won't happen by adding checks or handling errors.

edit

with your example:

> inp.split(' ')[1]
'12,'

on this part you run

.split(', ')

however since ', ' is not present in '12,', this string is not split, so you cannot take the second element.

Upvotes: 1

idar
idar

Reputation: 610

if the string is 'add ', you'll have index out of range error in the last split:

In [74]: inp
Out[74]: 'add '

In [75]: (inp.split(' ')[1])
Out[75]: ''

In [76]: (inp.split(' ')[1]).split(', ')[1]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-76-2cd8aab4e893> in <module>
----> 1 (inp.split(' ')[1]).split(', ')[1]

IndexError: list index out of range

Upvotes: 0

Related Questions