简体   繁体   中英

Remove last symbol in row

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

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

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')

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")

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM