-1

Does anyone know how to make this code into an f-string (if possible):

print(">>> Multi-line Comment", data, sep="\n")

So if there is 2 or more components in data it would print each in a new line. The above code works, its was just bugging me that I could do it for a single line, but couldn't for multiline.

For example: This works for a single line

print(f">>> Single-line Comment\n{data}")

This will work for if I know how many multilines there are, in this case 2:

print(f">>> Multi-line Comment\n{str.splitlines(data)[0]}\n{str.splitlines(data)[1]}")

Any ideas to make an f-string version more automated like print(">>> Multi-line Comment", data, sep="\n")?

1 Answers1

0

Well, f-strings don't like \ns so you have to work around it. You can do it in a couple of ways:

data = """Comment1
Comment2"""

x = data.splitlines()

print(f'[>>> Multi-line Comment",{chr(10)}{x[0]},{chr(10)}{x[1]}]')

or "fake" it:

nl = "\n"
print(f'[>>> Multi-line Comment",{nl}{x[0]},{nl}{x[1]}]')

In either case, the output should be:

[>>> Multi-line Comment",
Comment1,
Comment2]
Jack Fleeting
  • 24,385
  • 6
  • 23
  • 45
  • I guess its just better to go without an f-string in this, since f-strings don't the same flexibility. – tcraigmate Mar 05 '21 at 21:48
  • @tcraigmate You may be right at least in this case; but generally speaking, f-string are the best way, in my opinion, to inject variables into strings, so I tend to use them whenever possible. – Jack Fleeting Mar 05 '21 at 23:05