[Tutor] [Re] Fwd: Strings backwards

Victor Bouffier victor at grupocdm.com
Thu Jan 19 19:51:41 CET 2006


This was just posted by John Fouhy (snipped part of it):

        Basically, the syntax is [start:stop:step].
        
        If step is negative, you work backwards.  eg:
        >>> string.lowercase[20:10:-2]   # letters 20, 18, 16, 14, 12
        'usqom'
        
        And if you omit the start or stop parameters, and step is
        negative,
        then start defaults to the end of the list and stop to the
        beginning.
        
        So string.lowercase[::-1] will step backwards, starting at the
        end and finishing at the start.

So to reverse a string, you would only need to do the following:

>>> print 'hello world'[::-1]
dlrow olleh

I had to do the string-to-list-then-reverse-string-then-back-to-string
process myself before knowing about this marvelous operand.
It works on tuples (all immutable objects) too:

>>> digits = (0,1,2,3,4,5,6,7,8,9)
>>> print digits[::-1]
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)

Best of Luck
Victor

On Thu, 2006-01-19 at 08:26 +0100, János Juhász wrote:
> Hi Ryan,
> 
> I just extended Adam's code with a speech-to-text recepi from
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114216.
> 
> On 18/01/06, ryan luna <ryan_gm at sbcglobal.net> wrote:
> >
> > Hello, what i need to do is get user input and then
> > print the string backwards ^^ i have no idea how to do
> > that,
> >
> > print "Enter a word and i well tell you how to say it
> > backwards"
> >
> > word = raw_input("Your word: ")
> >
> > print word
> >
> > all that is simple enough im sure printing it out
> > backwards is to, just dont know how ^^, thanks for any help.
> 
> import sys
> from win32com.client import constants
> import win32com.client
> import string
> 
> speaker = win32com.client.Dispatch("SAPI.SpVoice")
> print "Type word or phrase, then enter."
> print "Ctrl+Z then enter to exit."
> 
> def backword(word):
>    l = list(word)
>    l.reverse()
>    return ''.join(l)
> 
> def backsentence(sentence):
>    words = sentence.split(' ')
>    words = [backword(word) for word in words]
>    return ' '.join(words)
> 
> while 1:
>    try:
>       s = raw_input()
>       rev = backsentence(s)
>       print 'I would say: ', rev
>       speaker.Speak(rev)
>    except:
>       if sys.exc_type is EOFError:
>          sys.exit()
> 
> It works on my xp :)
> 
> 
> Yours sincerely,
> ______________________________
> János Juhász
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list