Removing initial whitespace plus the last empty new line line using python
Question:
I am trying to implement a code that prints an 8 by 8 matrix (0 to 63). It should however remove the initial tab spaces and the last empty line. My code is below :
s =''
for i in range(n):
for j in range(n):
z = i * n + j
s += ' '
if z < 10:
s += ' '
s += str(z)
s += 'n'
print(s)
The image Below is also the desired output
I have tried the dedent function but it fails to remove the last line as well
Answers:
Could you try
n = 8
print("n".join([" ".join(["{:2d}".format(i*n+j) for j in range(n)]) for i in range(n) ]), end="")
Output:
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63
Basically all you are looking for is whenever you go to a new line, the initial space is not printed, since every newline is a j, you will need to add:
if j != 0:
s += ' '
It should work. Will look like this now:
s =''
for i in range(n):
for j in range(n):
z = i * n + j
if j != 0:
s += ' '
if z < 10:
s += ' '
s += str(z)
if i != j:
s += 'n'
print(s)
Let me know if it has any problems.
I am trying to implement a code that prints an 8 by 8 matrix (0 to 63). It should however remove the initial tab spaces and the last empty line. My code is below :
s =''
for i in range(n):
for j in range(n):
z = i * n + j
s += ' '
if z < 10:
s += ' '
s += str(z)
s += 'n'
print(s)
The image Below is also the desired output
I have tried the dedent function but it fails to remove the last line as well
Could you try
n = 8
print("n".join([" ".join(["{:2d}".format(i*n+j) for j in range(n)]) for i in range(n) ]), end="")
Output:
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63
Basically all you are looking for is whenever you go to a new line, the initial space is not printed, since every newline is a j, you will need to add:
if j != 0:
s += ' '
It should work. Will look like this now:
s =''
for i in range(n):
for j in range(n):
z = i * n + j
if j != 0:
s += ' '
if z < 10:
s += ' '
s += str(z)
if i != j:
s += 'n'
print(s)
Let me know if it has any problems.