Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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""")

Maybe even use three print statements:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading