Home > Enterprise >  How to add space in between set amount of characters in Python?
How to add space in between set amount of characters in Python?

Time:01-19

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"

CodePudding user response:

Try the following in python

string=" 3212345678"
n=3
string=string[0:n] " " string[n:]
string
' 32 12345678'

CodePudding user response:

You can split you string and add spaces at defined index.

def insert_space(string):
    return string[:3]   " "   string[3:4]   " "   string[4:7]   " "   string[7:9]   " "   string[9:]
    
str_num = " 3212345678"

print(insert_space(str_num))

Output

 32 1 234 56 78

CodePudding user response:

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))
  •  Tags:  
  • Related