0

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?

user3667089
  • 2,996
  • 5
  • 30
  • 56

2 Answers2

1

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")
M4C4R
  • 356
  • 4
  • 13
  • I wonder why python wouldn't allow us to simply write the more readable `print(f"""AAA{"\nBBB" if printbbb else ""}`. Otherwise, I think your second solution will work for my situation. – user3667089 May 05 '23 at 16:46
  • @user3667089 https://stackoverflow.com/questions/44780357/how-can-i-use-newline-n-in-an-f-string-to-format-output – Haoliang May 05 '23 at 16:48
  • 1
    This works though: `nl='\n' ; print(f"""AAA{f"{nl}BBB" if printbbb else ""}""")`, and this too: `nl='\n'; print(f"""AAA{f"{nl}BBB" * printbbb}""")` – Swifty May 05 '23 at 16:57
0

Here is an easy way to replace the space.

printbbb = False
print(f"""AAA
{'BBB' if printbbb else ''}
CCC""".replace('\n\n', '\n'))
peerpressure
  • 390
  • 4
  • 19
  • This works for the minimal example, but in the actual use case, the f-string is large, and it contains valid `\n\n` outside of the if-else that shouldn't be replaced to `\n` – user3667089 May 05 '23 at 16:41