1

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
1
  • You should mark this question as answered, please. Commented Oct 10, 2012 at 10:57

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thus, the OP should use >= instead of >.
1

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):

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.