Search code examples
pythonpython-3.xprintingcharacterseparator

How to remove/delete last character from printed list in python


I am creating simple program which finds the smallest multiplicators of a number (not sure if this is the right term). However, I can not find a way to delete last "*" from the listed result. What am I doing wrong? Please help.

num = int(input("write number: "))
print(num, end = "=")
div = 2
while num > 1:
    if num % div == 0:
        num = num / div
        print(div, end = "*")
    else:
        div += 1

Result I got:

24=2*2*2*3*

Result I want:

24=2*2*2*3

I tried to use sep="" instead of end="", tried \b, [:-1] but this does not work or I am just doing it wrong. Thank you.


Solution

  • One option is simply to check whether or not num =1 before printing the "*"

    num = num / div
    if num == 1 :
        print(div)
    else :
        print(div, end = "*")
    

    Since you only want to print a * if there are more multipliers to come, and there will always be another multiplier if div is more than 1.