[Tutor] Hmm...I should be able to figure this out...but...

Bob Gailer bgailer at alum.rpi.edu
Tue Jul 20 22:42:44 CEST 2004


At 01:22 PM 7/20/2004, Steven Combs wrote:
>I am using the following code to simply take user input and return the 
>results backwards.
>
>---------------------------------------------------------------
># Initialize Variables
>string = ""
>stringlength = 0
>
># Begin Program
>
>string = raw_input("Enter a string and I will display it backwards.\n")
>stringlength = len(string)
>
>for i in range (stringlength, 0, -1):
>     print string [i - 1],
>
>print "\n"
>
>raw_input("\nPress the enter key to exit")
>
>---------------------------------------------------------------
>
>It works, but it places a space in between the characters displayed.
>For instance, if the string entered is:
>
>Test
>
>the results are displayed
>
>t s e T

print puts a space after each ,. The easiest way to do what you want is to 
collect the letters in a string and print the string:

output = ''
for i in range (stringlength, 0, -1):
   output += i
print output

There are numerous other ways to do this, including reverse(), slicing, 
stdout,write(), et al.

>I tried using "\b" to backspace after each character is displayed, but 
>this didn't work.  I'm embarrassed to admit that I am trying to give this 
>as an assignment for a basic computer programming course I teach (I'm 
>stilling trying to learn the finer points of Python myself).  I know I 
>could use other commands, but I have to limit the command set for the 
>students at this stage in their programming section (we have yet to 
>discuss mutability and immutability)  Any suggestion for an easy fix?

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625 home
720 938 2625 cell 



More information about the Tutor mailing list