Preliminaries For this lab you will be working with regular expressions in Pytho
ID: 3720170 • Letter: P
Question
Preliminaries For this lab you will be working with regular expressions in Python. Various functions for working with regular expressions are available in the re module. Fortunately, Python makes it pretty easy to see if a string matches a particular pattern At the top of the file we must import the re module: import re Then we can use the search () function to test whether a string matches a pattern. In the example below, the regular expression has been saved in a string called pattern for convenience: phone123-456-7890' if re.search (pattern, phon else: e): print The string matches the pattern.' print ('The string does not match the pattern.') CSE 101 - Spring 2018 Lab #13 Page 1 The r that precedes the pattern string is not a typo. Rather, the r indicates that the string is a "raw" string. In a raw string, as opposed to a "normal" string, any backslash character is interpreted as simply a backslash, as opposed to defining an escape sequence like or . Make sure you use raw strings in your Python code when defining regular expressio The * and $ at the beginning and end of the regular expression indicate that the entire string must match the regular expression, and not just part of the string. Make sure you include these symbols in your regular expressions too!Explanation / Answer
Here is simple implementation of required method with test method import re def package_destination(package_code, country_codes): pattern = r'^d{3}-d{3}-[A-Z]d{1}$' if re.search(pattern, package_code): country_code = package_code.split("-")[0] # Get the first 3 digits if country_code in country_codes.keys(): return country_codes[country_code] else: return "error" if __name__ == '__main__': package_code = '898-524-0' country_codes = { '898': 'Kuwait', '312': 'Russia' } print package_destination(package_code, country_codes)