0
$\begingroup$

I have a phone number column in my dataset which has numbers in different formats. Here are some examples:

1000101000
111-101-1000
(212)-212-2122
444.456.7890
123 456 7890
+12124567890

How do I format all of the above different formats to (111) 111-1111 format?

$\endgroup$
1
  • $\begingroup$ Do you want to keep country codes or not? $\endgroup$ Jul 13 at 2:00
0
$\begingroup$
#txt is your phone number that you get from your dataset
filterTxt = list(filter(str.isdigit, txt))
formatTxt=''
for index,number in enumerate(filterTxt) :
 if index==0:
   formatTxt+='('+number
 elif index==2:
   formatTxt+=number+') '
 elif index==5:
   formatTxt+=number+'-'
 else:
   formatTxt+=number

Ok let me explain my code. First of all we want to filter only the number the easiest way is to use list(filter(str.isdigit, txt)). Filter will read all the string and compare it with str.isdigit which is to detect whether the string is digit or not and because we got the number already I then we just format it using for since we got the list of number already.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.