This post contains a total of 27+ Hand-Picked Python Program examples to Reverse a String, with Source Code. All the Programs are made using Python Programming language.
You can use the source code of these programs for educational use with credits to the original owner.
Related Posts
Click a Code to Copy it.
1. By Harshita Verma
Made by Harshita Verma. Simple Python program to reverse a string using Stack. ( Source )
# Function to add an item to stack .
def push(stack,item):
stack.append(item)
#Function to remove an item from stack.
def pop(stack):
if len(stack) == 0: return
return stack.pop()
# A stack based function to reverse a string
def reverse(string):
n = len(string)
# Create a empty stack
stack=[]
# Push all characters of string to stack
for i in range(0,n,1):
push(stack,string[i])
# Making the string empty since all characters are saved in stack
string=""
# Pop all characters of string and put them back to string
for i in range(0,n,1):
string+=pop(stack)
return string
string="Harshita"
string = reverse(string)
print("Reversed string is " + string)
2. By Vladimir Goman
Made by Vladimir Goman. In case you need to change the name in other places, enter them separated by a space. This code will return the name and surname in the reverse order. ( Source )
print(" ".join(input().title().split(" ")[::-1]))
3. By priya
Made by priya. ( Source )
# reverse string
print(input()[::-1])
4. By Daniel SΔvescu
Made by Daniel SΔvescu. A simple program to reverse a string. ( Source )
#Reverserd String
user_input = input("Enter a string : ")
reversed_string = user_input[::-1]
print("Original String Is : ", user_input)
print("Reversed String Is : ", reversed_string)
5. By Pedro Maimere
Made by Pedro Maimere. Enter your text string to reverse it. ( Source )
# Simple output:
#print(input()[::-1])
# Returns original and reversed inputs:
(lambda t:print("Original input:",t,"","Reversed input:",t[::-1],sep="\n"))(input())
6. By Chigozie Anyaeji π³π¬
Made by Chigozie Anyaeji π³π¬. ( Source )
#One liner revearse string
#for 2 minute coding challenge
string = input()
re = string[::-1]
print ("The revearse of string: "+ string+" is")
print (re)
7. By Yusra
Made by Yusra. ( Source )
st=input("enter a string:")
for a in range(-1,(-len(st)-1),-1):
print(st[a],end="")
8. By LayB
Made by LayB. A program that reverses a string. It works with web links too. ( Source )
s = input("Enter your phrase: ")
newS = s[::-1]
print (newS)
9. By Yaseen Akbari
Made by Yaseen Akbari. ( Source )
#Reverse String
#Enter your text...
word = input()
print(word[::-1])
10. By Aibek T.
Made by Aibek T. Python program to reverse a string using slicing. Just a code snippet for reversing a string the pythonic way. This technique is called slicing. ( Source )
s = input()
print('Input string:', s)
s = s[::-1] #reverse by slicing
print('Reversed str:', s)
11. By Lothar
Made by Lothar. Reverse integer number without using any string function. ( Source )
'''
This version shows how to reverse an integer number. Using a string from the number and retrieve the reverse value with a slice is very common. But as you can see there is also an other possibility to do so.
'''
buf = []
'''
The input is done in a way that the input value will be converted from string (all inputs are strings) to int. To store the input integer as splitted digits (separated) a for loop together with the input() function is used. The complete expression is embraced with brackets []. This enables to store the digits as a list. "list2 = list(int(x) for x in input('Enter integer number: '))" is also possible. Integer 254 will show as [2, 5, 4].
'''
list2 = [int(x) for x in input('Enter integer number: ')]
print('Input is: ',*list2, sep ='')
'''
To iterate through the separated digits a for loop with an additional enumerator is used. Variable i holds the digit and val the "index". Calculation is done by the modulo operator and using the remainder. The individual digits will then be multiplied with 10 and the power of the index. Result of this step is appended to a list buf. Final step is to calculate the sum of buf.
'''
for val, i in enumerate(list2):
buf.append((i % 10)*10**val)
print('Result is: ',sum(buf))
12. By Mohamed Arshad
Made by Mohamed Arshad. ( Source )
string1=input("")
length=len(string1)
i=0
for a in range(-1,(-length-1),-1):
print(string1[i],"\t",string1[a])
i+=1
13. By Richard Myatt
Made by Richard Myatt. Simple Python program to reverse a string. ( Source )
# Function to reverse a string
def reverseString(str):
return str[::-1]
text = input()
print("The string you entered is: %s" % text)
print("The reverse of this string is: %s" % reverseString(text))
14. By ManishA Sahu
Made by ManishA Sahu. PROGRAM TO REVERSE EACH WORD OF ENTERED STRING. ( Source )
s=input('Enter string:')
print(s)
Q=''
L=s.split(' ') #convert str. into List
for i in L:
x=i[len(i)::-1] #reverse of word
Q=Q+x+' ' #adding to a new str.
print("NEW STR. : ",Q)
15. By Smith Welder
Made by Smith Welder. Enter your string in line ‘put = “tset deeps”‘. ( Source )
import time
def timer(label='', trace=True):
class Tester:
def __init__(self, func):
self.func = func
self.alltime = 0
def __call__(self, *args, **kargs):
start = time.process_time()
result = self.func(*args, **kargs)
elapsed = time.process_time() - start
self.alltime += elapsed
if trace:
print (f'{label} {self.func.__name__}: {elapsed:.2f} {self.alltime:.2f}')
return result
return Tester
#print(f'{input()[::-1]}') vs print(''.join(reversed(input())))
put = "tset deeps"
@timer(label ="string")
def f(v):
#print(f'{v[::-1]}')
return f'{v[::-1]}'
@timer(label ="reversed")
def r(v):
#print(''.join(reversed(v)))
return ''.join(reversed(v))
for func in(f,r):
print(" ")
result = func(put)
func(put*10000)
func(put*200000)
func(put*3000000)
func(put*5000000)
print(result)
print(f'allTime = {func.alltime:.2f} sec')
16. By Srivikas M
Made by Srivikas M. ( Source )
def rev(str1):
str2=" "
i=len(str1)-1
while i>=0:
str2+=str1[i]
i-=1
return str2
word=input("Enter a string:")
print("The mirror of the string is ",rev(word))
17. By Kala Nandini
Made by Kala Nandini. Enter the string in line print(string_reverse(‘1234abcd’)) to get the reversed . ( Source )
def string_reverse(str1):
rstr1 = ''
index = len(str1)
while index > 0:
rstr1 += str1[ index - 1 ]
index = index - 1
return rstr1
print(string_reverse('1234abcd'))
18. By Tharun Kumar
Made by Tharun Kumar. ( Source )
startmsg = input()
endmsg = ""
for i in range(0,len(startmsg)):
endmsg = startmsg[i] + endmsg
print(endmsg)
19. By Nithish
Made by Nithish. Python program to reverse a text string. ( Source )
n=input("Enter Your Name :\n ")
f=len(n)
for i in range(f):
print(f-i," ",n[i:][::-1])
20. By Neha Nikam
Made by Neha Nikam. String reverse using a user defined function. ( Source )
def reverser(squares):
lst=[]
for num in squares[::-1]:
lst.append(num)
return lst
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = reverser(squares)
print(squares)
21. By Mike Shaw
Made by Mike Shaw. ( Source )
#Python reverse trick
rev = input('Enter something to reverse: \n')
print('The reverse of your input is: ', rev[::-1])
22. By Abhishek Gupta
Made by Abhishek Gupta. ( Source )
string=input("enter a string:")
print(string)
print("the",string,"in reverse order is:")
length=len(string)
for a in range(-1,(-length-1),-1):
print(string[a])
23. By Abdul Jalil
Made by Abdul Jalil. A small python program to reverse a string. ( Source )
word = str(input())
rev = word[::-1]
print(rev)
24. By Ahamed Sheriff
Made by Ahamed Sheriff. ( Source )
string=input()
reversed_string=''.join(reversed(string))
print(reversed_string )
25. By Adrian
Made by Adrian. It takes the string, then flips it and reverses it. ( Source )
x = str(input()) # Stores user input.
def reverseIt(x): # Define function.
i = 0 # Counter variable.
w = [] # Empty list.
for n in range(len(x)): # Start loop.
i -= 1 # Index counter.
w.append(x[i]) # Append list.
w = ''.join(w) # Join list together.
print(w) # Print new string.
reverseIt(x) # Call function.
26. By Glitched
Made by Glitched. ( Source )
class ForChallenges:
def string_slicer(s):
for i in range(1,len(s)+1):
print(s[-i])
if __name__ == '__main__':
ForChallenges.string_slicer(input(""))
27. By Bart Claw
Made by Bart Claw. Reverse a string using recursive. ( Source )
def revString(inS):
if len(inS) == 1:
return inS
else:
return inS[-1] + revString(inS[0:-1])
someString = "Reverse it!"
print(revString(someString))
28. By Harinder Singh
Made by Harinder Singh. ( Source )
n=str(input())
rev=n[::-1]
print(rev)