Hoops
Hoops

Reputation: 863

String index out of range Python

Trying to write a code at the moment that basically tests to see if the letter that lies at r (so here (2,3)) is equal to a particular letter or string.

def test():

txt = "test.txt"
r = (2,3)
if txt[r[0]][r[1]] == 'l':
    return (True)
elif txt[r[0]][c[1]] == "m":
    return (False)
elif txt[r[0]][c[1]] == "b":
    return (True)

But i keep getting an error. The error dialogue is this:

if txt[r[0]][r[1]] == 'l':
IndexError: string index out of range

I have no idea what im doing wrong considering i had it working earlier today. Also, before you ask, i have to code it this way for a particular reason.

Thanks.

Upvotes: 2

Views: 1128

Answers (3)

sberry
sberry

Reputation: 132018

What are you trying to do? What would your return be?

The reason it doesn't work is this:

r = (2,3)
txt[r[0]][r[1]] -> txt[2][3]

txt[2] == 's'
s[3] -> IndexError

As mentioned by @Abhijit, if you are trying to grab the character by doing a slice, then

txt[r[0]:r[1]] is correct.

However, if you are always doing a slice that grabs one character, meaning your r tuple is always of the form (N, N+1), like (2, 3), then you may want to change your strategy.

Note that for your given example you could do:

if any([letter in txt for letter in ['l', 'b']]):
    return True

If you need to check for actual slices in the text and not just a single character, then the above will still work.

if any([letter_group in txt for letter_group in ['te', 'st']]):
    return True

or even:

if any([letter in txt for letter in 'lb']]):
    return True

for example...

Upvotes: 3

Simeon Visser
Simeon Visser

Reputation: 122376

You don't need to do a slice to check if a character is present at a certain location. For example:

txt = 'test.txt'
if txt[2] == 's':
    print 'runs'

So if you coordinate is (2, 3) then you only need to use the first value:

txt = 'test.txt'
coord = (2, 3)
if txt[coord[0]] == 's':
    print 'runs'

Upvotes: 1

Abhijit
Abhijit

Reputation: 63737

Please note,

if txt[r[0]][r[1]] == 'l':

should be written as

if txt[r[0]:r[1]] == 'l':

and similarly other usage should be changed

Upvotes: 4

Related Questions