2

I'd like to print a message with a list separated by \n inside an f-string in python3.

my_list = ["Item1", "Item2", "Item3"]
print(f"Your list contains the following items:\n\n{my_list}")

Desired output:

# Your list contains the following items:
#    Item1
#    Item2
#    Item3
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69

3 Answers3

8

One possible solution, chr(10) evaluates to newline:

my_list = ["Item1", "Item2", "Item3"]
print(f"Your list contains the following items:\n{chr(10).join(my_list)}")

Prints:

Your list contains the following items:
Item1
Item2
Item3
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    Nice! I was scratching my head around something similar... – dawg May 10 '20 at 19:58
  • @Andrej Kesely this works, but where it gains by being one line, in my mind it looses for lack of clarity. If you put this in your code, you would want to document that `chr(10)`evaluates to a newline. In which case you aren't even one line. I personally would go with the clarity of keeping the `\n` and splitting the `join()` to a separate line from the print, but that may just be me. Might be useful as a debugging print that you don't leave in the code I guess. – Glenn Mackintosh May 10 '20 at 20:07
  • @GlennMackintosh Yeah, it's not *production* level code. Myself, I would go with separate `'\n'.join(...)` - it's more clear. – Andrej Kesely May 10 '20 at 20:09
4

use join() (see the docs for join here)

joined_list = '\n'.join(my_list)
print(f"Your list contains the following items:\n{joined_list}")

I know that you specifically asked for an f string, but really I would just use the older style:

print("Your list contains the following items:\n%s" %'\n'.join(my_list))
Glenn Mackintosh
  • 2,765
  • 1
  • 10
  • 18
  • f strings cannot expression portion cannot contain a backslash. This is a syntax error. – dawg May 10 '20 at 19:54
  • 1
    @dawg just ran it and noticed that. Edited to correct..@Andrej Kesely Looks like yuo cannot do it all inside the f string and have to break it up because of the `\n` you want for a separator. – Glenn Mackintosh May 10 '20 at 19:58
3

You can use a helper function:

>>> my_list = ["Item1", "Item2", "Item3"]
>>> def cr(li): return '\n'.join(li)
... 
>>> print(f"Your list contains the following items:\n{cr(my_list)}")
Your list contains the following items:
Item1
Item2
Item3

To get your precise example:

>>> def cr(li): return '\n\t'.join(li)
... 
>>> print(f"Your list contains the following items:\n\t{cr(my_list)}")
Your list contains the following items:
    Item1
    Item2
    Item3
dawg
  • 98,345
  • 23
  • 131
  • 206