Logo
/
Programming
/
Python Course
/

Data Aggregation (Strings)

Python: Data Aggregation (Strings)

Like with number aggregation, string aggregation involves not knowing what the strings contain and how big they are.

Imagine a function that knows how to multiply a string; it repeats it a specified number of times:

repeat('hexlet', 3)  # 'hexlethexlethexlet'

The principle of how this function works is that in the loop, the string is “incremented” a specified number of times:

def repeat(text, times):
    # The neutral element for strings is an empty string
    result = ''
    i = 1

    while i <= times:
        # Each time we add the string to the result
        result = result + text
        i = i + 1

    return result

Let's break down the code's execution into steps:

# To call repeat('hexlet', 3)
result = ''
result = result + 'hexlet'  # hexlet
result = result + 'hexlet'  # hexlethexlet
result = result + 'hexlet'  # hexlethexlethexlet

Instructions

Implement the function sanitize_phone_number(), which takes a phone number from a form and returns a string without spaces, parentheses, and hyphens.

Users type phone numbers in different ways, but applications often store them in one format. Go through the source string character by character and build a new phone number only from useful characters.

sanitize_phone_number('+7 (999) 123-45-67')  # '+79991234567'
sanitize_phone_number('8 800 555 35 35')     # '88005553535'
sanitize_phone_number('(123) 456-7890')      # '1234567890'

If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:

  • Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Found a bug? Have something to add? Pull requests are welcome!