forked from mckrd/py_repo_beginner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse_string.py
40 lines (31 loc) · 1.11 KB
/
reverse_string.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#This program is to find reverse of a string - all inputs are taken from user.
# The below methods are to find reverse of a string
def reverse_slicing(s):
return s[::-1]
def reverse_for_loop(s):
s1 = ''
for c in s:
s1 = c + s1 # appending chars in reverse order
return s1
def reverse_while_loop(s):
s1 = ''
length = len(s) - 1
while length >= 0:
s1 = s1 + s[length]
length = length - 1
return s1
def reverse_join_reversed_iter(s):
s1 = ''.join(reversed(s))
return s1
def reverse_list(s):
temp_list = list(s)
temp_list.reverse()
return ''.join(temp_list)
if __name__ == "__main__":
# Taking inputs from user
input_str = input("Please input a string: ")
print('Reverse String using slicing =', reverse_slicing(input_str))
print('Reverse String using for loop =', reverse_for_loop(input_str))
print('Reverse String using while loop =', reverse_while_loop(input_str))
print('Reverse String using join and reversed =', reverse_join_reversed_iter(input_str))
print('Reverse String using list reverse =', reverse_list(input_str))