[Python] How to replace and remove certain characters in a string conditionally?

Discussão em 'Python' iniciado por Stack, Setembro 2, 2025.

  1. Stack

    Stack Membro Participativo

    I'm incorporating a quadratic equation solver inside a calculator as a first project.

    After taking the inputs, the code displays the equation as this:

    1x^2 + -3x + 2 = 0

    How do I strip the "1" as a coefficient from all instances of x in case of "1" and "-1" being inputs?

    Also, remove the "+" and replace it with a "-" sign if the input is negative?

    Thank you!

    Here's the code:

    if choice == '3':
    print(f'\n{"Quadratic Equation Form":-^24}\n{"ax^2 + bx + c = 0":^24}\n')

    a = int(input('Please enter a: '))
    if a == 0 or a == '0':
    print('Highest degree coefficent cannot be 0')
    continue

    b = int(input('Please enter b: '))

    c = int(input('Please enter c: '))

    #display eq
    if b == 0 or 0:
    quadr_eq = f'\n{f"{a}x^2 + {c} = 0":^24}'
    else:
    quadr_eq = f'\n{f"{a}x^2 + {b}x + {c} = 0":^24}'
    print(quadr_eq)

    delta = b**2 - 4*a*c

    #solve formula
    x1 = (-b + (delta) ** 0.5) / (2 * a)
    x2 = (-b - (delta) ** 0.5) / (2 * a)

    #defining discriminants
    ans_string = ""

    if delta > 0:
    ans = [x1, x2]
    ans_string += f'{"Two real and distinct solutions: " f"{ans}":^24}'

    elif delta == 0:
    ans = [x1]
    ans_string += f'{"One real solution: " f"{ans}":^24}'

    elif delta:
    ans_string += f'No real solution'




    solved_quadr = f'\n{"Solution":^24}\n{ans_string}\n'
    print(solved_quadr)


    quit_program = input('Quit program? (Y/N): ')

    if quit_program.lower() == 'y':
    break

    solver()

    Continue reading...

Compartilhe esta Página