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.
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'"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With