Match Pattern and Replace - Hands On
Match Pattern and Replace - Hands On
Match Pattern and Replace - Hands On
1. Match Pattern and Replace
1. Write a function subst which replaces a pattern matching portion with another value.
2. Using subst, replace all the words ROAD with RD in the following:
addr = ['100 NORTH MAIN ROAD', '100 BROAD ROAD APT.', 'SAROJINI DEVI ROAD', 'BROAD AVENUE ROAD']
3. Use the Test against custom input box to output the result for debugging.
4. Use print(res) to display the output.
Expected Output:
['100 NORTH MAIN RD.', '100 BROAD RD. APT.', 'SAROJINI DEVI RD.', 'BROAD AVENUE RD.']
addr = ['100 NORTH MAIN ROAD', '100 BROAD ROAD APT.', 'SAROJINI DEVI ROAD', 'BROAD AVENUE ROAD']
['100 NORTH MAIN RD.', '100 BROAD RD. APT.', 'SAROJINI DEVI RD.', 'BROAD AVENUE RD.']
#!/bin/python3
import sys
import os
import io
import re
# Complete the function below.
def subst(pattern, replace_str, string):
#susbstitute pattern and return it
def main():
addr = ['100 NORTH MAIN ROAD',
'100 BROAD ROAD APT.',
'SAROJINI DEVI ROAD',
'BROAD AVENUE ROAD']
#Create pattern Implementation here
#Use subst function to replace 'ROAD' to 'RD.',Store as new_address
return new_address
'''For testing the code, no input is required'''
if __name__ == "__main__":
f = open(os.environ['OUTPUT_PATH'], 'w')
res = main();
f.write(str(res) + "\n")
f.close()
#!/bin/python3
import sys
import os
import io
import re
# Complete the function below.
def subst(pattern, replace_str, string):
return re.sub(pattern,replace_str,string)
#susbstitute pattern and return it
def main():
addr = ['100 NORTH MAIN ROAD',
'100 BROAD ROAD APT.',
'SAROJINI DEVI ROAD',
'BROAD AVENUE ROAD']
#Create pattern Implementation here
#Use subst function to replace 'ROAD' to 'RD.',Store as new_address
new_address=[]
for i in addr:
new_address.append(subst(r' ROAD',' RD.',i))
return new_address
'''For testing the code, no input is required'''
if __name__ == "__main__":
f = open(os.environ['OUTPUT_PATH'], 'w')
res = main();
f.write(str(res) + "\n")
f.close()
<h3> Output: </h2>
<pre class="prettyprint">
['100 NORTH MAIN RD.', '100 BROAD RD. APT.', 'SAROJINI DEVI RD.', 'BROAD AVENUE RD.']
</pre>
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.