[Tutor] [Re] Fwd: Strings backwards
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
And if you omit the start or stop parameters, and step is
then start defaults to the end of the list and stop to the
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]
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
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
> 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)
> return ''.join(l)
> def backsentence(sentence):
> words = sentence.split(' ')
> words = [backword(word) for word in words]
> return ' '.join(words)
> while 1:
> s = raw_input()
> rev = backsentence(s)
> print 'I would say: ', rev
> if sys.exc_type is EOFError:
> It works on my xp :)
> Yours sincerely,
> János Juhász
> Tutor maillist - Tutor at python.org
More information about the Tutor