0

I am trying to ask the user for their phone number, and many people type their number such as "123-456-7890", "(123)456-7890".

I want to make the program strip the " ()- " from the input so that when I print the number back to the user, it shows it as 1234567980 without all the extra characters.

So far I have been able to remove only the first parentheses from the string by doing this:

number = str(input("Enter phone number: "))
print(number.strip('('))
Xenic
  • 1
  • 1
  • 2

2 Answers2

2

Strings are iterable, so your problem can be efficiently solved using a list comprehension.

digits = '0123456789'
phone_number = ''.join([x for x in input("Enter phone number: ") if x in digits])

The benefit of this approach is that ONLY digits get included in the final result. Whereas with the replace approach you have to specify each and every exclusion.

Karnage
  • 477
  • 2
  • 9
0

Maybe not the most elegant way to do it but:

print(number.replace('(', '').replace(')', '').replace('-', ''))
Yevhen Kuzmovych
  • 5,476
  • 3
  • 19
  • 36