Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write the following in Python, please provide step by step commenting and explan

ID: 3702524 • Letter: W

Question

Write the following in Python, please provide step by step commenting and explanation (preferrably in regex but im not understanding it fully, thanks) We are given a string S representing a phone number, which we would like to reformat. String S consists of N characters: digits, spaces and/or dashes. It contains at least two digits. Spaces and dashes in string S can be ignored. We want to reformat the given phone number in such a way that the digits are grouped in blocks of length three, separated by single dashes. If necessary, the final block or the last two blocks can be of length two. For example, given string S = "00-44 48 5555 8361", we would like to format it as "004-448-555-583-61". Write a function that, given a string S representing a phone number, returns this phone number reformatted as described above. For example, given S = "00-44 48 5555 8361", the function should return "004-448-555-583-61". Given S ="0 - 22 1985--324",the function should return "022-198-53-24". Given S = "555372654", the function should return "555-372-654". Assume that N is an integer within the range [2..100]; string S consists only of digits (0?9), spaces and/or dashes (-); string S contains at least two digits.

Explanation / Answer

Here is a step by step code to do the same # Import regular expression library import re if __name__ == '__main__': S = '00-44 48 5555 8361' # Define regular expression to express spaces and dashes [ s for spaces ] # [s-]* means zero or more spaces or dashes regex = '[s-]*' # Split the phone number to get rid of dashes and spaces # tokens will be an array of number strings # tokens = ['00','44','48','5555', '8361'] tokens = re.split(regex, S) # Re join the numbers to form the string of numbers only # phone_str = '00444855558361' phone_str = "".join(tokens) print phone_str # Reformat string in groups of three or two # If there are more than 4 characters create a group of 3 and repeat # Else create a group of two and repeat reformatted_array = [] temp = phone_str while len(temp) > 0: if len(temp) > 4: n = 3 elif len(temp) > 3: n = 2 else: reformatted_array.append(temp) break current = temp[0:n] reformatted_array.append(current) temp = temp[n:] # print reformatted array ['004', '448', '555', '583', '61'] print reformatted_array reformatted_string = "-".join(reformatted_array) # reformatted_string - 004-448-555-583-61 print reformatted_string