2
n = int(input("Enter a number :-"))
for i in range(1, 11):
    print(i*n, end = ",")

When I tried this program, in output I have got a comma in the last position. But I don't want this comma. How can I remove the comma? I just code it for a multiplication table.

Output: 8,16,24,32,40,48,56,64,72,80,

Zoe
  • 27,060
  • 21
  • 118
  • 148

4 Answers4

1

You can check the index before printing

n = int(input("Enter a number :-"))
for i in range(1, 11):
    end = "," if i < 10 else ""
    print(i*n, end = end)
Ken4scholars
  • 6,076
  • 2
  • 21
  • 38
1

Python lets you do this easily with join:

n = int(input("Enter a number: "))
print(','.join(str(i*n) for i in range(1, n)))  # surely, range(1, n) not range(1, 11)

For more complex situations, a common solution is to prefix each item except the first.

n = int(input("Enter a number: "))
sep = ""
for i in range(1, n):  # same fix here
    print("%s%i" % (sep, i*n), end = "")
    sep = ","   # add a delimiter on each subsequent iteration
tripleee
  • 175,061
  • 34
  • 275
  • 318
1

Produce a series which you pass into print all at once with a custom separator, instead of requiring to figure out the correct end-of-line in separate print calls:

print(*(i*n for i in range(1, 11)), sep=',')

This * unpacks the generator (i*n for i in range(1, 11)) as arguments to print, in essence being equivalent to:

print(8, 16, 24, ..., sep=',')
deceze
  • 510,633
  • 85
  • 743
  • 889
0

the best way to do this is using Join function

using Using generator expression:

def gen_num(n,count):
    for i in range(1, count):
        yield str(i*n)

print(",".join(list(gen_num(8,11))))

using list comprehension

n = 8
print(",".join([str(x*n) for x in range(1,11)]))

Result: 8,16,24,32,40,48,56,64,72,80

balaji k
  • 1,231
  • 1
  • 5
  • 5
  • 1
    FWIW, the `[]` are superfluous. You can use a *generator expression* instead of a list comprehension here. – deceze Mar 10 '21 at 07:09
  • @deceze Thanks for suggestion: I have updated generator expression also in it. – balaji k Mar 10 '21 at 09:41
  • Uhm, no, that's an even more complex *generator function*. All I said was `print(",".join(str(x*n) for x in range(1,11)))` is sufficient… – deceze Mar 10 '21 at 09:57