Phil
Phil

Reputation: 3

Printing a list with variable spacing

I am looking for python3 code to take a list of 81 numbers like this:

003020600900305001001806400008102900700000008006708200002609500800203009005010300

and print it in a 9x9 metric format like this with more space between horizontal numbers:

003020600 900305001 001806400
008102900 700000008 006708200
002609500 800203009 005010300

Upvotes: 0

Views: 81

Answers (3)

Rakesh
Rakesh

Reputation: 82795

Use slicing

Ex:

s =  '003020600900305001001806400008102900700000008006708200002609500800203009005010300'

for i in range(0, len(s), 27):
    val = s[i:i+27]
    print( " ".join(val[j:j+9] for j in range(0, len(val), 9)) )

Output:

003020600 900305001 001806400
008102900 700000008 006708200
002609500 800203009 005010300

Edit as per comment.

for i in range(0, len(s), 27):
    val = s[i:i+27]
    for j in range(0, len(val), 9):
            print(" ".join(val[j:j + 9]))

Output:

0 0 3 0 2 0 6 0 0
9 0 0 3 0 5 0 0 1
0 0 1 8 0 6 4 0 0
0 0 8 1 0 2 9 0 0
7 0 0 0 0 0 0 0 8
0 0 6 7 0 8 2 0 0
0 0 2 6 0 9 5 0 0
8 0 0 2 0 3 0 0 9
0 0 5 0 1 0 3 0 0

Upvotes: 1

Sohaib Aslam Sameja
Sohaib Aslam Sameja

Reputation: 76

For SPACES AND LINE BREAKS

st = '003020600900305001001806400008102900700000008006708200002609500800203009005010300'
metric_size = 9
space_interval = 3
index = 1

for i in range(0, len(st), metric_size):

    print(st[i:i + metric_size], end=' ')

    if index%space_interval == 0:
        print()

    index += 1

OUTPUT

003020600 900305001 001806400 
008102900 700000008 006708200 
002609500 800203009 005010300 

FOR LINE BREAKS

st = '003020600900305001001806400008102900700000008006708200002609500800203009005010300'
metric_size = 9
space_interval = 3
index = 1

for i in range(0, len(st), metric_size):

    print(st[i:i + metric_size])

    if index%space_interval == 0:
        print("---------")

    index += 1

OUTPUT

003020600
900305001
001806400
---------
008102900
700000008
006708200
---------
002609500
800203009
005010300
---------

Upvotes: 0

jpp
jpp

Reputation: 164823

Here's one way which assumes you supply the number of digits per number and numbers per row.

x = '003020600900305001001806400008102900700000008006708200002609500800203009005010300'

num_len = 9
num_row = 3

L = [x[i:i+num_len] for i in range(0, len(x), num_len)]
res = (L[j:j+num_row] for j in range(0, len(L), num_row))

print(*(' '.join(i) for i in res), sep='\n')

003020600 900305001 001806400
008102900 700000008 006708200
002609500 800203009 005010300

Upvotes: 0

Related Questions