Lomore
Lomore

Reputation: 217

python 'string index out of range' error

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

Upvotes: 0

Views: 321

Answers (3)

skovorodkin
skovorodkin

Reputation: 10284

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

Upvotes: 2

opwid
opwid

Reputation: 56

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)

Upvotes: 1

Nf4r
Nf4r

Reputation: 1410

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.

Upvotes: 0

Related Questions