I have a list of phone numbers and these need to be written in a certain way.
As for now they're listed as "+3212345678" and I wish the add spaces in between characters after certain amounts of numbers.
Result should be "+32 1 234 56 78"
I have a list of phone numbers and these need to be written in a certain way.
As for now they're listed as "+3212345678" and I wish the add spaces in between characters after certain amounts of numbers.
Result should be "+32 1 234 56 78"
You can use the format method with unpacking to provide it with each individual character as arguments. This will let you control the separators and get fancy formatting capabilities:
sep = "({}{}{}) {} {}{}{}.{}{}.{}{}" # {} are placeholders for digits
t = "+3212345678"
f = sep.format(*t)
print(f)
(+32) 1 234.56.78
You could extend this to using a dictionary for different formats depending on the length of the phone number (or other attributes):
seps = { 6:"{}{}.{}{}.{}{}",
7:"{}{}{}.{}{}.{}{}",
8:"{}{} {}{}.{}{}.{}{}",
10:"({}{}) {} {}{}{}.{}{}.{}{}",
11:"({}{}{}) {} {}{}{}.{}{}.{}{}" }
t = "+3212345678"
f = seps[len(t)].format(*t)
print(f)
"(+32) 1 234.56.78"
t = "44345678"
f = seps[len(t)].format(*t)
print(f)
"44 34.56.78"
Try the following in python
string="+3212345678"
n=3
string=string[0:n]+" "+string[n:]
string
'+32 12345678'
You can make a list which stores the number of characters space_list
before a space, and add each character to a new list in a nested loop based on your space_list
which adds a space right after the inner loop.
def format_num(space_list: list):
fmt_num = ""
count = 0
for space in space_list:
for s in range(space):
fmt_num += phn_num[count]
count += 1
fmt_num += " "
return fmt_num
phn_num = "+3212345678"
spaces = [3, 1, 3, 2, 2]
print(format_num(spaces))