Search code examples
pythonpython-3.xf-string

How to avoid creating a newline when using if-else in f-string expression


Please see the below minimal example,

printbbb = True
print(f"""AAA
{'''BBB''' if printbbb else ''}
CCC""")

This prints

AAA
BBB
CCC

as desired, however, if I set printbbb to False, it prints

AAA

CCC

How can I change the code so that it will print

AAA
CCC

when printbbb is set to False?


Solution

  • You could use a list to improve readability:

    printbbb = True
    
    to_print = ["AAA"]
    if printbbb:
        to_print.append("BBB")
    to_print.append("CCC")
    print("\n".join(to_print))
    

    Or you could conditionally add a newline character:

    nl = "\n"
    printbbb = True
    print(f"""AAA{nl + "BBB" if printbbb else ""}
    CCC""")
    

    Another variation by Swifty:

    nl = "\n"
    printbbb = True
    print(f"""AAA{f"{nl}BBB" * printbbb}
    CCC""")
    

    Maybe even use three print statements:

    printbbb = True
    print("AAA")
    if printbbb:
        print("BBB")
    print("CCC")