1

I am trying to answer a question for a homework assignment. I have to split an input of numbers into a phone number. The input is 8005551212 and the output needs to look like 800-555-1212.

My question is that I do not know how to specifically split a section of the numbers. I figured out how to use % to select the rightmost digits. Now, I just need to isolate 800 and 555.

Thank you so much!

ellie1
  • 33
  • 2
  • 4
  • Depending on how complex the input can be, e.g. will it always just be 10 digits, or can there be other symbols already present, do you have to account for errors in the numbers, country codes, etc., I suggest starting with looking at strginslices, then moving to regular expressions. – bicarlsen Jun 14 '21 at 21:27
  • 1
    Are you always guaranteed that the input is going to be 10 characters long with the need to be formatted as xxx-xxx-xxxx? – Sudheesh Singanamalla Jun 14 '21 at 21:27

5 Answers5

3

I would convert the phone number to a string then use Python fstrings to do the rest:

s_num = str(num) # num being the phone number integer
f'{s_num[:3]}-{s_num[3:6]}-{s_num[6:]}' # this is the result

Keep in mind, this is rather limited and will not scale to differing length country codes, extensions, etc.

Adin Ackerman
  • 202
  • 1
  • 7
1

The solution for your problem is pretty simple:

a = '8005551212'
print(f'{a[:3]}-{a[3:6]}-{a[6:]}')
blazej
  • 927
  • 4
  • 11
  • 21
0

You can try this:

n = '8005551212'

# Simple Solution
'-'.join([n[:3],n[3:6],n[6:]])
# Out[29]: '800-555-1212'

# General Solution
ix = [0,3,6]
'-'.join([n[i:j] for i,j in zip(ix, ix[1:]+[None])])
# Out[21]: '800-555-1212'
Andreas
  • 8,694
  • 3
  • 14
  • 38
0

Another solution, using re:

import re

s = "8005551212"

s = re.sub(r"(\d{3})(\d{3})(.*)", r"\1-\2-\3", s)
print(s)

Prints:

800-555-1212
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

Provided that the input will be 10 digits long, this can be a very simple 1 liner.

>>>num = "8005551212"
>>>req = "{}{}{}-{}{}{}-{}{}{}{}".format(*num)
>>>print(req)

 '800-555-1212'

The * unpacks the 10 digits into the {}

Muhd Mairaj
  • 557
  • 4
  • 13