Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more efficient way to convert this phone number to plain text?

Tags:

python

I want to convert a phone number with parentheses and a hyphen between the sixth and seventh digit to 10 numbers with no formatting. This code does the trick, but it's unwieldy and I was wondering whether there's a more efficient method?

Thanks!

phone_number = "(251) 342-7344"

phone_number=phone_number.replace("(","")
phone_number=phone_number.replace(")","")
phone_number=phone_number.replace(" ","")
phone_number=phone_number.replace("-","")

print phone_number
like image 532
goldisfine Avatar asked Jan 21 '26 18:01

goldisfine


1 Answers

You can use str.translate:

>>> from string import punctuation,whitespace
>>> strs = "(251) 342-7344"
>>> strs.translate(None, punctuation+whitespace)
'2513427344'

Using str.isdigit and str.join:

>>> "".join([x for x in strs if x.isdigit()])
'2513427344'

Timing comparisons:

>>> strs = "(251) 342-7344"*1000
>>> %timeit strs.translate(None, punctuation+whitespace)
10000 loops, best of 3: 116 us per loop                   #clear winner
>>> %timeit "".join([x for x in strs if x.isdigit()])
100 loops, best of 3: 4.42 ms per loop
>>> %timeit re.sub(r'[^\d]', '', strs)
100 loops, best of 3: 2.19 ms per loop
like image 130
Ashwini Chaudhary Avatar answered Jan 23 '26 07:01

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!