python-3.xbackspace

How to do a backspace in python


I'm trying to figure out how to print a one line string while using a for loop. If there are other ways that you know of, I would appreciate the help. Thank you. Also, try edit off my code!

times = int(input("Enter a number: "))
print(times)
a = 0
for i in range(times+1):
    print("*"*i)
    a += i
print("Total stars: ")
print(a)
print("Equation: ")
for e in range(1,times+1):
    print(e)
    if e != times:
        print("+")
    else:
        pass

Out:

Enter a number: 5
*
**
***
****
*****
Equation:
1
+
2
+
3
+
4
+
5

How do I make the equation in just one single line like this:

1+2+3+4+5

Solution

  • I don't think you can do a "backspace" after you've printed. At least erasing from the terminal isn't going to be done very easily. But you can build the string before you print it:

    times = int(input("Enter a number: "))
    print(times)
    a = 0
    for i in range(times+1):
        print("*"*i)
        a += i
    print("Total stars: ")
    print(a)
    print("Equation: ")
    equation_string = ""
    for e in range(1,times+1):
        equation_string += str(e)
        if e != times:
            equation_string += "+"
        else:
            pass
    print(equation_string)
    

    Basically, what happens is you store the temporary equation in equation_str so it's built like this:

    1
    1+
    1+2
    1+2+
    ...
    

    And then you print equation_str once it's completely built. The output of the modified program is this

    Enter a number: 5
    5
    
    *
    **
    ***
    ****
    *****
    Total stars: 
    15
    Equation: 
    1+2+3+4+5
    

    Feel free to post a comment if anything is unclear.