forked from codevscolor/codevscolor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_string.py
More file actions
37 lines (27 loc) · 939 Bytes
/
reverse_string.py
File metadata and controls
37 lines (27 loc) · 939 Bytes
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
# Reverse a string in different ways
# Method 1: for loop
def reverse_str(str):
rev_str = ''
for c in str:
rev_str = c + rev_str
return rev_str
given_str = input('Enter a string : ')
print('Reversed string is : {}'.format(reverse_str(given_str)))
# Method 2: Recursive
def reverse_str_recursive(str):
if len(str) == 0:
return str
else:
return reverse_str_recursive(str[1:]) + str[0]
given_str = input('Enter a string : ')
print('Reversed string is : {}'.format(reverse_str_recursive(given_str)))
# Method 3: reversed()
def reverse_str_reversed(str):
return ''.join(reversed(str))
given_str = input('Enter a string : ')
print('Reversed string is : {}'.format(reverse_str_reversed(given_str)))
# Method 4: String slicing
def reverse_str_slicing(str):
return str[::-1]
given_str = input('Enter a string : ')
print('Reversed string is : {}'.format(reverse_str_slicing(given_str)))