PDA

View Full Version : [SOLVED] Python: noob question about string indexes



NoJobyDesert
October 2nd, 2011, 06:34 PM
Is putting a variable in for the index of a string legal?

that is, if
my_str = "Hello World" then
print my_str[1] return 'e'.

but if I try this:

index = 1
print my_str[index]

I get this error:

IndexError: string index out of range

Is there some other way of using a variable for a given string index?

Arndt
October 2nd, 2011, 06:52 PM
Is putting a variable in for the index of a string legal?

that is, if
my_str = "Hello World" then
print my_str[1] return 'e'.

but if I try this:

index = 1
print my_str[index]

I get this error:

IndexError: string index out of range

Is there some other way of using a variable for a given string index?

Using variables as indices works perfectly well, so your original idea is correct. I can't say why you get an error - can you post a complete program that does this?

KdotJ
October 2nd, 2011, 06:58 PM
Using the code you posted above, works perfectly well... In your program, tha variable must at some point become greater than the length of the string before you use it as an index... Or, the string changes to something else (eg, to a single character assuming the code you posted)

simeon87
October 2nd, 2011, 07:49 PM
That error will only occur when my_str has one or less characters.

NoJobyDesert
October 2nd, 2011, 10:00 PM
Thanks all for the help.

Yes, this code was part of a loop, and the variable did in fact become higher than the length of the string at some point.