-3

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"

  • 3
    Please show us what you tried and what went wrong - https://stackoverflow.com/help/how-to-ask – matszwecja Jan 19 '22 at 13:55
  • You might find your answer here - What's the best way to format a phone number in Python? (https://stackoverflow.com/questions/7058120/whats-the-best-way-to-format-a-phone-number-in-python) – Herker Jan 19 '22 at 13:59
  • This might be the solution of what you looking for https://stackoverflow.com/questions/18221436/efficient-way-to-add-spaces-between-characters-in-a-string – Mario Jan 19 '22 at 14:00
  • Does this answer your question? [What's the best way to format a phone number in Python?](https://stackoverflow.com/questions/7058120/whats-the-best-way-to-format-a-phone-number-in-python) – Dave Potts Jan 20 '22 at 22:09

3 Answers3

3

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"
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

Try the following in python

string="+3212345678"
n=3
string=string[0:n]+" "+string[n:]
string
'+32 12345678'
Gadi
  • 76
  • 5
0

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))
Tharu
  • 188
  • 2
  • 14