0

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 .

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
user3934169
  • 13
  • 1
  • 1
  • 5

6 Answers6

2

You can reverse it with the slicing syntax:

s = input("Enter a string: ")
print s[::-1]
Enter a string: London
nodnoL
jedwards
  • 29,432
  • 3
  • 65
  • 92
1

print raw_input().lower()[::-1]

Abhishek Bhatia
  • 9,404
  • 26
  • 87
  • 142
0

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]
gboffi
  • 22,939
  • 8
  • 54
  • 85
-1

Using extended slice syntax: 'string_goes_here'[::-1]

Example : print('london'[::-1])

Online Compiler link

Extended Slices :

Ever since Python 1.4, the slicing syntax has supported an optional third step'' orstride'' 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.

--Reference

Tharif
  • 13,794
  • 9
  • 55
  • 77
-1
    s = input("Enter a string: ")
    s = s.lower()
    print s[::-1]
Sanch
  • 137
  • 7
-1

string=input('Enter String: ')

print (string[::-1])

string: heaven output:nevaeh

Roger Perez
  • 2,807
  • 29
  • 31