-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScript48_Book_S11_Ex10_Replace.py
More file actions
54 lines (40 loc) · 1.21 KB
/
Script48_Book_S11_Ex10_Replace.py
File metadata and controls
54 lines (40 loc) · 1.21 KB
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
48
49
50
51
52
53
54
# In the name of God
# Mohammad Hossein Zehtab
# python-evens-17
# S11 Book Ex10: Replace
def test(did_pass):
'''
Test if the statement is passed or not
'''
if did_pass:
print('OK')
else:
print('Failed')
def test_suite():
'''
Evaluates a group of tests
'''
test(replace("Mississippi", "i", "I") == "MIssIssIppI")
s = "I love spom! Spom is my favorite food. Spom, spom, yum!"
test(replace(s, "om", "am") ==
"I love spam! Spam is my favorite food. Spam, spam, yum!")
test(replace(s, "o", "a") ==
"I lave spam! Spam is my favarite faad. Spam, spam, yum!")
def replace(s, old, new):
'''
Replaces all occurrences of old with new in a string s
'''
ls = list(s)
for l in ls:
if len(old) == 1:
if l == old:
ls[ls.index(l)] = new
else: continue
else:
for j in range(len(old)):
if ls[ls.index(l) + j] == old[j]:
ls[ls.index(l) + j] = new[j]
else: continue
return ''.join(ls)
### Driver Code ###
test_suite()