Home > Software engineering >  I was told to reverse a number in python I did that but I can't remove comma after the last ele
I was told to reverse a number in python I did that but I can't remove comma after the last ele

Time:12-29

num=32768
x=0
y=0
while x<num:
    x=num
    y=num//10
    num=y
    print(x,end=',')

Here is my code the output shows 8,6,7,2,3, now how will I remove the comma after 3?

CodePudding user response:

Put the digits in a list, then use join() to print the list with comma delimiters.

num=32768
x=0
y=0
result = []
while x<num:
    x=num
    y=num//10
    num=y
    result.append(str(x))
print(",".join(result))

CodePudding user response:

you can do this in one line:

 ",".join(str(32768)[::-1])

CodePudding user response:

Use a ternary operator, for example:

num = 32768
x = 0
y = 0
while x < num:
    x = num % 10
    y = num // 10
    num = y
    print(x, end=',' if x < num else '')

CodePudding user response:

just add a condition to check if you have arrived at last number.

num=32768
x=0
y=0
while x<num:
    x=num
    y=num//10
    num=y
    if x >= num: 
        print(x, end='')
    else:
        print(x,end=',')


CodePudding user response:

A simpler approach (assuming you aren't expressly forbidden from doing it this way) is to convert the whole number to a string and then reverse it.

>>> num = 32768
>>> print(str(num)[::-1])
86723
>>> print(','.join(str(num)[::-1]))
8,6,7,2,3
  • Related