#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.