Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to add newline to .format() method?

I've been reading a textbook, and I came across an interesting problem, asking me to print an address like so using print statements:

John Doe
123 Main Street
AnyCity, AS 09876

I'm trying to actually figure out if it's possible to do it using one print statement, but I can't figure out how to add a newline using the .format() method in Python 3. Here's what I've tried:

>>> first = 'John'
>>> last = 'Doe'
>>> street = 'Main Street'
>>> number = 123
>>> city = 'AnyCity'
>>> state = 'AS'
>>> zipcode = '09876'
>>> 
>>> ("{0} {1}\n{2} {3}\n{4}, {5} {6}").format(first, last, number, street, city, state, zipcode)
'John Doe\n123 Main Street\nAnyCity, AS 09876'
>>>
>>> ("{0} {1}'\n'{2} {3}'\n'{4}, {5} {6}").format(first, last, number, street, city, state, zipcode)
"John Doe'\n'123 Main Street'\n'AnyCity, AS 09876"
>>>
>>> ("{0} {1}{7}{2} {3}{8}{4}, {5} {6}").format(first, last, number, street, city, state, zipcode, '\n', '\n')
'John Doe\n123 Main Street\nAnyCity, AS 09876'
>>>
>>> ("{0} {1} \n {2} {3} \n {4}, {5} {6}").format(first, last, number, street, city, state, zipcode)
'John Doe \n 123 Main Street \n AnyCity, AS 09876'

This is probably a super simple question and I'm just missing something really basic. Thanks for the help.

like image 838
Jose Magana Avatar asked Aug 16 '14 19:08

Jose Magana


2 Answers

It works if you print it. Please read this post explaining print vs repr.

print("{0} {1}\n{2} {3}\n{4}, {5} {6}".format(first, last, number, street, city, state, zipcode))

Output

John Doe
123 Main Street
AnyCity, AS 09876

If you just type a variable in IDLE, it actually will use repr, which is why it was represented as a single line.

>>> repr(("{0} {1}\n{2} {3}\n{4}, {5} {6}").format(first, last, number, street, city, state, zipcode))
"'John Doe\\n123 Main Street\\nAnyCity, AS 09876'"
like image 100
Cory Kramer Avatar answered Oct 17 '22 15:10

Cory Kramer


Not sure why I couldn't find this answer anywhere else but:

print("{}Walking time is: {:,.3f} hours{}".format("\n", walking_time, "\n"))

worked. Just insert the placeholders and then include the \n in the insert list.

like image 5
Howard Avatar answered Oct 17 '22 17:10

Howard