-2

Possible Duplicate:
Reverse a string in Python

Its been stumping me despite my initial thoughts that it would be simple.

Originally, I thought I would have have it print the elements of the string backwards by using slicing to have it go from the last letter to the first.

But nothing I've tried works. The code is only a couple lines so I don't think I will post it. Its extraordinarily frustrating to do.

I can only use the " for ", "while", "If" functions. And I can use tuples. And indexing and slicing. But thats it. Can somebody help?

(I tried to get every letter in the string to be turned into a tuple, but it gave me an error. I was doing this to print the tuple backwards which just gives me the same problem as the first)

I do not know what the last letter of the word could be, so I have no way of giving an endpoint for it to count back from. Nor can I seem to specify that the first letter be last and all others go before it.

3
  • 3
    Always post whatever code you have. Don't think twice before doing so. Commented Dec 20, 2012 at 18:37
  • Have you tried your_string[::-1]? Commented Dec 20, 2012 at 18:38
  • How should strings with newlines be treated? "foo\nbar" -> "oof\nrab" or "rab\noof"? Commented Dec 20, 2012 at 18:44

2 Answers 2

6

You can do:

>>> 'Hello'[::-1]
'olleH'

Sample

Sign up to request clarification or add additional context in comments.

4 Comments

Wow, awesome! And when i think that i was writing a loop... silly me
That, would have been helpful of the book to include....................................................................................
Python is all about the syntactic sugar.
@Mike yeah this is the reason we all love Python so much
0

As Mike Christensen above wrote, you could easily do 'Hello'[::-1].

However, that's a Python-specific thing. What you could do in general if you're working in other languages, including languages that don't allow for negative list slicing, would be something more like:

def getbackwards(input_string):
   output = ''
   for x in range(0,len(input_string),-1):
       output += input_string[x]
   return output

You of course would not actually do this in Python, but just wanted to give you an example.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.