-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLesson 1
49 lines (30 loc) · 1.19 KB
/
Lesson 1
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
40
41
42
43
44
45
46
47
# Write a function to reverse a string
string = 'This is the string'
length_of_the_string = len(string)
print(string[10]) # Prints the 11th character in the string, 0 indexed
print(range(10, 5, -1)) # Prints the [10, 9, 8, 7, 6]
for i in range(3):
print(string[i]) # Prints the ith character
print(range(len(string))) # Prints array of integers from 0 to n where n is the length of the string
# So use these functions and try to write a function to print the reverse of a string
# Method 1: Prints one character in each line (prints column wise)
def reverse_string(string):
length_of_the_string = len(string)
for i in range(len(string)- 1, -1, -1):
print(string[i])
string = 'This is the string'
reverse_string(string)
# Method 2: Prints all the characters in a single line
def reverse_string(string):
reversed_string = ''
length_of_the_string = len(string)
for i in range(len(string) - 1, -1, -1):
reversed_string += string[i]
return reversed_string
string = 'This is the string'
print(reverse_string(string))
# Method 3:
def reverse_string(string):
return string[::-1]
string = 'This is the string'
print(reverse_string(string))