0

I'm trying to code a word scrambler but when I try to append letters from my word, using index, I get the error 'String index out of range'. I have tried this without the 'input' but once I added it in I started getting problems. my code is:

a = input('word ->')
b = []
count = 0
while count < 5:
    b.append(a[count])
    count +=1
print(b)

it would be great if someone could help. thanks

1
  • if you have word shorter than 5 letters then you can't get 5th letter - and you get your error. BTW: you can use b = a[:5] Commented Oct 1, 2016 at 19:18

3 Answers 3

2

I'm not sure what you are trying to achieve here, but look at this:

word = input('word -> ')
b1 = []
# Iterate over letters in a word:
for letter in word:
    b1.append(letter)
print(b1)

b2 = []
# Use `enumerate` if you need to have an index:
for i, letter in enumerate(word):
    # `i` here is your `count` basically
    b2.append(letter)
print(b2)

# Make a list of letters using `list` constructor:
b3 = list(word)
print(b3)

assert b1 == b2 == b3
Sign up to request clarification or add additional context in comments.

Comments

1

Because when you give input smaller than 5 a[count] is out of index. So try this one:

a = input('word ->')
b = []
count = 0
while count < len(a):
    b.append(a[count])
    count +=1
print(b)

Comments

0

The problem is that your "count" will increase each loop until it reaches 5. If the string in the input is shorter than 5, you will get index error.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.