Home > Back-end >  Remove last symbol in row
Remove last symbol in row

Time:11-22

My code is:

n = 3
for i in range(1, n 1):
    for j in range(1, n 1):
        print(j*i, end='*')
    print(end='\b\n')

Result of this code is:

1*2*3*
2*4*6*
3*6*9*

But I need expected result like this (without aesthetics in end of rows):

1*2*3
2*4*6
3*6*9

CodePudding user response:

Use '*'.join() instead of the end parameter in print()

for i in range(1, n   1):
    print('*'.join(f'{j * i}' for j in range(1, n   1)), end='\n')

Output

1*2*3
2*4*6
3*6*9

CodePudding user response:

Solution:

n = int(input())
for i in range(1, n 1):
    for j in range(1, n 1):
        if(j*i == n*n):
             print(j*i)
        else:
             print(j*i, end='*')
        
    print(end='\b\n')

CodePudding user response:

Using list comprehension we create a list to print in one line and then you can use '*' to expand the list. Then we use 'sep' (separator) param of print function to join them

n = 3
for i in range(1, n 1):
    print(*[j*i for j in range(1, n 1)], sep='*', end="\n")

CodePudding user response:

Just check if you're not at the last value in the range. If you aren't print '*' if you are don't do anything. View the below code for clarification.

n = 3
for i in range(1, n 1):
    for j in range(1, n 1):
        print(j*i, end='')
        if j != n:
           print('*', end='')
    print(end='\b\n')
  • Related