I am working on a script that takes the user input and reverses the whole input. for example if the user inputs "London" it will be printed as "nodnol" . I am currently being able to reverse the order of a certain number of letters but not being able to reverse the entire string .
-
1`print raw_input().lower()[::-1]` – Abhishek Bhatia Feb 05 '16 at 15:02
6 Answers
You can reverse it with the slicing syntax:
s = input("Enter a string: ")
print s[::-1]
Enter a string: London nodnoL

- 29,432
- 3
- 65
- 92
I'm under the impression that you cannot use any of the nice things that make Python a soo nice language, so here it is my low-key answer...
At the beginning, we have a string,
>>> ast = input('Tell me a word of your choice: ') # <--- "London"
We can compute its length using the len
builtin
>>> last = len(ast) # <--- 6
now we want to index the string in reverse, the string indices are 0 ... 5
so we need the sequence 5 4 3 2 1 0
>>> for i in range(last): print(last-1-i)
5
4
3
2
1
0
Let's see that we can access the characters of the string in reverse using the indexing scheme above
>>> for i in range(last): print(ast[last-1-i])
n
o
d
n
o
L
Finally, we have to build the reversed string, using the +
operator and starting from the null string
>>> rast = ""
>>> for i in range(last): rast += ast[last-1-i]
>>> print(rast)
nodnoL
>>>
To summarize
ast = input('Tell me a word of your choice: ')
last = len(ast)
rast = ""
for i in range(last):
rast += ast[last-1-i]

- 22,939
- 8
- 54
- 85
Using extended slice syntax: 'string_goes_here'[::-1]
Example : print('london'[::-1])
Extended Slices :
Ever since Python 1.4, the slicing syntax has supported an optional third
step'' or
stride'' argument. For example, these are all legal Python syntax: L[1:10:2], L[:-1:1], L[::-1]. This was added to Python at the request of the developers of Numerical Python, which uses the third argument extensively. However, Python's built-in list, tuple, and string sequence types have never supported this feature, raising a TypeError if you tried it. Michael Hudson contributed a patch to fix this shortcoming.

- 13,794
- 9
- 55
- 77
string=input('Enter String: ')
print (string[::-1])
string: heaven output:nevaeh

- 2,807
- 29
- 31