Python3 – print list separated with \n inside an f-string

Viewed 1849

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
3 Answers

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

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

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
Related