Mohammad Yasin
Mohammad Yasin

Reputation: 31

How to add space in data/String using python?

I have some data in my database. It looks like 84819010 and I wanted to make it like 8481 90 10 I use the following code and get the following error:

information_table = data.cur.execute("""
                    SELECT p.gs_com_code, p.gs_code FROM product p
                    INNER JOIN (
                    SELECT pp.p_gs_com_code From product_purchase pp
                    ) t ON t.p_gs_com_code = p.gs_com_code                           
                         """,).fetchall()

for info in information_table:
    t = info[1]
    sep = "{}{}{}{} {}{} {}{}"
    gs_code = sep.format(*t)
    print(gs_code)

Error:

    gs_code = sep.format(*t)
IndexError: Replacement index 7 out of range for positional args tuple

My information looks like 84819010 and I wanted to make it like 8481 90 10

Upvotes: 1

Views: 115

Answers (1)

Corralien
Corralien

Reputation: 120399

Use f-strings:

for info in information_table:
    gs_code = f"{info[:4]} {info[4:6]} {info[6:]}"
    print(gs_code)

# Output
6804 22 00
7018 10 00
8712 00 00
6804 22 00

Upvotes: 1

Related Questions