Python Forum
I am trying to reverse a string using loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I am trying to reverse a string using loop
#1
Hi, I recently started learning python, I read this blog and trying to implementing it.

I am getting stuck, I can't use ".join(reversed(string)) or string[::-1] methods here

Here is what my code looks like:

def reverse(text):
    while len(text) > 0:
        print text[(len(text)) - 1],
        del(text[(len(text)) - 1]
The error that I an getting is, invalid syntax on del(text[(len(text)) - 1]

Please suggest to me where I went wrong.

Thank you!
buran write Apr-27-2023, 08:07 AM:
Spam link removed
Yoriz write Sep-28-2021, 12:16 PM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
Python 3 print needs to be used with ()
to get the last item of text text[(len(text)) - 1] can be replaced with text[-1]
to get all but the last item text = text[:-1]
def reverse(text):
    while len(text) > 0:
        print(
            text[-1]
        )
        text = text[:-1]
codinglearner likes this post
Reply
#3
Thank you for the quick response, I will try this.
Reply
#4
Count the number of open parentheses ( and close parentheses ) in:
del(text[(len(text)) - 1]
If the number is not the same then that is a problem.
Reply
#5
Hi,

you know all these simple things we amateurs want to try, someone has already done them.

Have a look here.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Loop through a list of string oldtrafford 4 1,485 Mar-24-2022, 05:30 PM
Last Post: deanhystad
  Loop through a list of string oldtrafford 3 1,711 Feb-15-2022, 04:42 PM
Last Post: snippsat
  loop for dynamic cut string - cleaner way? korenron 4 1,953 Nov-22-2021, 02:30 PM
Last Post: korenron
  printing a string in reverse Skaperen 2 1,557 Nov-20-2021, 05:08 AM
Last Post: ghoul
  Convert string to JSON using a for loop PG_Breizh 3 2,986 Jan-08-2021, 06:10 PM
Last Post: PG_Breizh
  Reverse a String ragav_in 3 2,199 Jul-24-2020, 02:24 AM
Last Post: ragav_in
  String slicing and loop iteration divyansh 9 4,757 Jun-07-2020, 10:29 PM
Last Post: divyansh
  while loop reading list in reverse Jerry51 1 1,580 Apr-24-2020, 12:44 PM
Last Post: deanhystad
  Reverse the string word sneha 2 2,640 Dec-12-2019, 03:37 AM
Last Post: sneha
  String slicing in python from reverse ift38375 1 2,411 Apr-29-2019, 06:58 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020