简体   繁体   中英

Python: How to add a new line with a variable inside of the print function

In Python, I'm aware that '\\n' adds a new line when using a string inside of a print call. But how do I add a new line when using a variable inside of the print function?

For example:

print("\nHello") # <----- string used, no issues here

produces

>>> print("\nHello")

Hello

Now suppose I have a list named guest_list . How would I do something akin to " print('\\n'guest_list) ", printing an empty line and then the list?

Thanks for any help offered!

You can pass an empty string as the first argument and sep='\\n' if you want to avoid formatting/concatenation before printing.

>>> guest_list = [1, 2, 3]
>>> print('', guest_list, sep='\n')

[1, 2, 3]

... or equivalently:

>>> print('\n', guest_list, sep='')

[1, 2, 3]

Or convert to string, then add '\\n' to it:

>>> l=[1,2,3]
>>> print('\n'+str(l))

[1, 2, 3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM