0

Hello (this is my first question on the site so apologies if i have not followed an rules) Below are two codes (using for loop) that I have written to print reverse of a string input by the user. One code gives me an error and the other works fine. I cannot understand why. Why is the function "range" seem to make the difference? Appreciate if someone can help me understand the logic - many thanks

Code 1: That gives me error:

string = input('Enter a Word ')
length = len(string)
reverse = []

for i in string:
    x=string [-1-i]
    reverse.append(x)

print (reverse)

*Enter a Word Python


TypeError Traceback (most recent call last) in 4 5 for i in string: ----> 6 x=string [-1-i] 7 reverse.append(x) 8 TypeError: unsupported operand type(s) for -: 'int' and 'str'

Code 2: This works fine

string = input('Enter a Word ')
length = len (string)
reverse = []

for i in range(length):
    x=string [-1-i]
    reverse.append(x)

print (reverse)

*Enter a Word Python

['n', 'o', 'h', 't', 'y', 'P']*

Haseeb Haque
  • 25
  • 1
  • 1
  • 5

3 Answers3

1

The first loop you are doing is creating a foreach loop for your string, therefore your "i" is basically a char. Do you know there is also a function called "reverse()"?

vikAy
  • 314
  • 6
  • 15
  • Thanks no I did not and thanks for pointing it out. But i really want to understand why one code, above, works and the other does not – Haseeb Haque Apr 12 '20 at 01:09
  • can you please explain the difference between the functions reverse() and reversed () – Haseeb Haque Apr 13 '20 at 02:36
  • does this answer your question https://stackoverflow.com/questions/6810036/whats-better-the-reverse-method-or-the-reversed-built-in-function – vikAy Apr 13 '20 at 07:40
0

With for i in string, i will take the value of each character in the string, e.g. 'H', 'e', 'l', 'l', 'o' if the input was 'Hello'.

When you call string[-1-i], Python is trying to subtract a string from a number, which is why you get the error unsupported operand type(s) for -: 'int' and 'str'.

Irfan434
  • 1,463
  • 14
  • 19
0

You can make a reverse function easily -

def reverse(word = ""):
  return word if len(word) < 2 else reverse(word[1::]) + word[0]

myword = "bookkeepper"

print(myword+reverse(myword))
# bookkeepperreppeekkoob
Mulan
  • 129,518
  • 31
  • 228
  • 259
  • Thank you for the input - what i really want to understand is that how come the second code works and the first does. Both follow pretty much the same logic except for the range function. many thanks – Haseeb Haque Apr 12 '20 at 01:04