I have a list in python that I am printing to the screen. The current format is

Option Key: [0, 3, 6, 8, 8, 5, 2, 0, 7, 1, 9, 5, 0, 7, 7, 4, 2]

I would like it to be Option Key: 0 3688 5207 1950 7742

I think I need to do something with the .format method but I"m not sure.

The code looks like this

    option_key.append(int(m_key_code))

    print("Option Key: ", option_key)

Recommended Answers

All 3 Replies

Without thinking ...

mylist = [0, 3, 6, 8, 8, 5, 2, 0, 7, 1, 9, 5, 0, 7, 7, 4, 2]

s = ""
n = 1
for ix, k in enumerate(mylist):
    if ix == n:
        s += ' '
        n += 4
    s += str(k)

print(s)  # 0 3688 5207 1950 7742

Very good. It can be improved with n = len(mylist) % 4.

Another concept of Python is slicing ...

mylist = [0, 3, 6, 8, 8, 5, 2, 0, 7, 1, 9, 5, 0, 7, 7, 4, 2]

s = "".join(str(n) for n in mylist)

s2 = "0"
for n in range(0, 17, 4):
    s2 += " " + s[n+1:n+5]

print(s2)    # 0 3688 5207 1950 7742
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.