-1

I'd like to write a basic program which copy the content from variable 'a' to variable 'b' but in reverse order, e.g.: a="toy" to b="yot"

My code:

a="toy"
index= len(a)
indexm=0
new=" "

while(index>0):
    new[indexm]==a[index]
    index=index-1
    indexm=indexm+1

print(new)

I've got the following error message:

IndexError: string index out of range
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-56-c909e83737f5> in <module>()
      5 
      6 while(index>0):
----> 7     new[indexm]==a[index]
      8     index=index-1
      9     indexm=indexm+1
IndexError: string index out of range

I would like to solve it without using built-in functions to learn programmer thinking. Thank you in advance

CsCs
  • 43
  • 1
  • 1
  • 7
  • 5
    `b = a[::-1]` should do it – gold_cy Mar 27 '17 at 17:25
  • 1
    You have at least three mistakes in your program. First, you need `new+=a[index]` instead of `==`. Second, you must initialize the `index` to `len(a)-1`. Thirst, the condition should be `index>=0`. This is a classical so-called "off-by-one" error. – DYZ Mar 27 '17 at 17:29
  • 2
    Possible duplicate of [Reverse a string in Python](http://stackoverflow.com/questions/931092/reverse-a-string-in-python) – Tadhg McDonald-Jensen Mar 27 '17 at 17:29
  • you are getting the error because you are trying to access `a[3]` when `a`'s indexes are only `0`, `1`, and `2`. – TehTris Mar 27 '17 at 17:29
  • Thanks DYZ, you were right! this is the solution! – CsCs Mar 27 '17 at 17:37

1 Answers1

1

try this:

a="toy"
index= len(a)
indexm=0
new=""

while(index>0):
    new += a[index-1]
    index=index-1
    indexm=indexm+1

print(new)
xudesheng
  • 1,082
  • 11
  • 25