Reputation: 7
I'm working on a project for my CS class and I was wondering if there was anyway to make the following code shorter or more efficient:
data_numb = str(input("Input Data, then press enter: "))
phone_numb = int(''.join(list(filter(str.isdigit, data_numb))))
phone_numb2 = str(phone_numb)
list1 = list(phone_numb2)
list1.insert(0, "(")
list1.insert(4, ") ")
list1.insert(8, "-")
print("".join(list1))
Upvotes: 0
Views: 47
Reputation: 332
You could do
data_numb = input("Input Data, then press enter: ")
p = ''.join(list(filter(str.isdigit, data_numb)))
res = '('+p[:3]+') '+p[3:6]+'-'+p[6:]
print(res)
by inserting by hand.
Upvotes: 1
Reputation: 20414
You could concatenate sub-strings to shorten the code:
print('(' + phone_numb2[:3] + ') ' + phone_numb2[3:6] + '-' + phone_numb2[6:])
Or with f-strings (Python 3.6 or above):
print(f'({phone_numb2[:3]}) {phone_numb2[3:6]}-{phone_numb2[6:]}')
which I find neater.
Upvotes: 2