user4139413
user4139413

Reputation:

How to print a string backwards using a for loop

I have to create a program that lets the user enter a string and then, using range, the program outputs that same string backwards. I entered this into python, but it goes me an error, in the 4th line, it says 'int' object has no attribute '__getitem__'. Can someone please help me correct it? (Using range)

user=raw_input("Please enter a string: ")
user1=len(user)-1
for user in range(user1,-1,-1):
    user2=user[user1]
    print user2

Upvotes: 4

Views: 10207

Answers (5)

Aaron Hall
Aaron Hall

Reputation: 395423

I think you have a mistake because you keep using the same words to describe very different data types. I would use a more descriptive naming scheme:

user = raw_input("Please enter a string: ")
user_length = len(user)
for string_index in range(user_length - 1, -1, -1):
    character = user[string_index]
    print(character)

For example, if the user input was foo, it would output:

o
o
f

Upvotes: 3

spacether
spacether

Reputation: 2699

Python 3 solution:

user=input("Please enter a string: ")
for ind in range(1,len(user)+1):
    char = user[-ind]
    print(char)

And another non for loop solution is:

''.join(reversed(user))

Upvotes: 0

cherish
cherish

Reputation: 1400

your user has been overwrited in your for loop. Take this(Use range)

user=raw_input("Please enter a string: ")
print ''.join([user[i] for i in range(len(user)-1, -1, -1)])

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 114025

This is because you are overwriting the string user with an int in the line for user in range(...)

Perhaps you'd be better off with:

user=raw_input("Please enter a string: ")
for user1 in range(len(user)-1,-1,-1):
    user2=user[user1]
    print user2

Upvotes: 0

smac89
smac89

Reputation: 43186

You are overwriting the user string with your for-loop, fix it by changing the for-loop variable

Fix:

for ind in range(user1,-1,-1):
    user2 = user[ind]
    print (user2)

Alternative (without for-loop):

print user[::-1]

Upvotes: 0

Related Questions