Trying to reverse a string using a while loop & other specific conditions

Question:

So here is the deal, I need to reverse a user-defined string without using [::-1] or a reverse function call. I think I have a found a possible solution but I don’t know enough about python to troubleshoot why it does not work, why can’t I take the position of a string using an index?

name= str((input("Enter the name: ")))

i = len(name)

while i in range(len(name)) > 0:
    print(name[i], end = '')
    i = i - 1
Asked By: Spencer

||

Answers:

The following code, will work, and will reverse a string.


        def reverseString(s: List[str]) -> str:
            left, right = 0, len(s) -1
            while left < right:
                s[left], s[right] = s[right], s[left]
                left += 1
                right -=1 
            return s

Use this:

for i in range(len(name) - 1, -1, -1):
    print(name[i], end="")

Explaining the arguments in the range(), from left to right:

  1. start: the value (index) i starts from
  2. stop: the value where i stops exclusive by step
  3. step: increment or decrement (-1 implies the decrement is by 1)
Answered By: Geeky Quentin

If we were to correct the solution you have provided, it would be this:

name= str((input("Enter the name: ")))
i = len(name) - 1

while i >= 0:
    print(name[i], end = '')
    i = i - 1
Answered By: M B

A better way to do it in the manner you are attempting is to use a for loop and count backwards through the string indices.

for i in range(1, len(name) + 1):
  print(name[-i])

This will iterate through a range of numbers (from 1 to n) and count backaward along your string by calling the negative indices of the string. 'helloworld'[-1] = d ...[-2] = l ...[-3] = r etc.

Answered By: Ben

the following code will work:

    a = input("enter your name: ")
    for b in range(len(a)-1, -1, -1):
          print(a[b], end = "")
Answered By: Akshat kushwaha
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.