It feels so good, so quick and not C!

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Mon Mar 17 20:58:56 EST 2003


> From: BB [mailto:bbondi at pacbell.net]
> 
> print "This is a prompt. Enter a string to be reversed: ",
> sOrig = raw_input()#get a string to work on
> sRev=""#init
> char_count=len(sOrig)#now I have the string length
> while ((char_count - 1) >= 0):#loop thru string backwards, zero based
>    char_count = char_count - 1
>    sRev = sRev+sOrig[char_count]#create the reverse string
> print sRev

This suffers from a number of problems:

1. It is *slow* (string concatenation).
2. It uses a lot of memory (string concatenation).
3. It is needlessly complex.

The following two programs will do what you want a lot better.

Python 2.2 and earlier (will also work with later versions)

    print "This is a prompt. Enter a string to be reversed: ",
    sOrig = raw_input()

    # Create a list where each element is the corresponding
    # character in sOrig
    lRev = list(sOrig)

    # Reverse the list
    lRev.reverse()

    # Create a string by joining the elements of the reversed
    # list (characters) together with no characters between them
    sRev = ''.join(lRev)

    print sRev

Python 2.3 and later

    print "This is a prompt. Enter a string to be reversed: ",
    sOrig = raw_input()

    # Create a reversed copy of sOrig using an extended slice
    sRev = sOrig[::-1]
    print sRev

In addition to the above string-specific specific cases, the general
case is better done as:

    orig = (1, 2, 3,)  # iterable object - in this case a tuple
    rev = list(sOrig)
    rev.reverse()
    rev = tuple(orig)  # convert back to the original type

Tim Delaney





More information about the Python-list mailing list