If you are new to Python and you don’t know how to reverse a string in Python, here is a sample script using default reverse method [::-1]:
print ("Enter a String")
mystr = input()
#reverse using [::-1]
revstr = mystr[::-1]
print ("Reverse is: "+revstr)
The output of the above program:
Enter a String
superman
Reverse is: namrepus
So basically using [::-1], it is possible to reverse a string, but in interviews, sometimes to test your logical programming skill they may ask you to write a program to reverse a string without using the default reverse method.
The solution for the above question is to write a custom reverse() function in Python.
Here is the solution:
def reverse(InputStr):
#find the length of the string
#then subtract by 1, because
#we all know array starts with 0
i = len(InputStr) - 1
rev = ''
#now loop through each character
#and then store each character in
#a new variable rev and return
while i >= 0:
rev = rev + str(InputStr[i])
i = i - 1
return rev
#here is the usage of the above function
print (reverse('spiderman'))
The above code is well commented, read them to understand.
Are you a Python web developer?, you may need this script!!
This is the Python web script version of reversing a string without using default method:
#!/usr/bin/python
print "Content-type: text/html\n\n";
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
#custom reverse function
def reverse(InputStr):
i = len(InputStr) - 1
rev = ''
while i >= 0:
rev = rev + str(InputStr[i])
i = i - 1
return rev
#get the string from form and store it in mystring
mystring = form.getvalue('string')
print '''
<html>
<body>
<h3>Web Based Python script to Reverse a string without using default reverse method [::-1]</h3>
<form action="" method="post">
<label>Enter a word or a sentence<label>
<input type="text" name="string" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
'''
#print only if form is submitted
if(mystring):
print "<p>Reverse is: <strong>" + reverse(mystring) + "</strong></p>"
The same custom reverse() function is used in the Python web script also, read the comments to understand the other features in the above script such is submitting a form, storing the form value in a variable, calling a function etc.,
And finally the demo of the web script,
