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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With