plahstic
plahstic

Reputation: 1621

String index out of range error

Hey i keep getting a string index out of range error... i have tried EVERYTHING could you please help out, Thanks a hell of a lot appreciated.

x = 0
y = ""
z = 0
user_input = raw_input("Message? ")

while z < len(user_input):
    y = y + " " + user_input[x]
    x = x +3
    z += 1
    if x > len(user_input):
         print y
         break

Upvotes: 1

Views: 288

Answers (3)

Simeon Visser
Simeon Visser

Reputation: 122356

You only break when if x > len(user_input):. But what if x % 3 == 0?

That means the length of your input string is dividable by three. You increment x by three each time and when the length of your input string is a multiple of three you'll get an error.

To fix it, you should use if x >= len(user_input): instead.

Upvotes: 3

JoeLinux
JoeLinux

Reputation: 4307

if user_input is a multiple of 3, then x will eventually equal the length of user_input (and the index will be one greater than actually exists).

user_input = "abc"

If someone answers your user_input with that, then you'll have a length of 3, but the index will only go up to 2 (user_input[0] == "a", user_input[1] == "b", user_input[2] == "c", user_input[3] throws an IndexError).

Instead, change your if statement to look like this:

while x >= len(user_input):

Upvotes: 1

Miron Brezuleanu
Miron Brezuleanu

Reputation: 3060

Maybe your if condition should read x >= len(user_input)? (user_input[x] with x being len(user_input) is probably giving you trouble)

Upvotes: 0

Related Questions