I have a question about styling in PEP 8 (or cutting the number of characters in each line to be smaller).
Consider that I have a book
with a bunch of different attributes and I want to concatenate them into some String.
books = [book_1, book_2, book_3]
for b in books:
print("Thank you for using our Library! You have decided to borrow %s on %s. Please remember to return the book in %d calendar days on %s" %
(book.title, book.start_date, book.lend_duration, book.return_date"))
How can I shorten this line to ensure its readability?
Any ideas will help. PEP 8 is just 1 idea.
PEP 8 suggests lines should be limited to 79 characters. This is because it allows you to have multiple files open next to one another, while also avoiding line wrapping. Of course, keeping statements to 79 characters or less is not always possible. PEP 8 outlines ways to allow statements to run over several lines.
PEP 8 is a document that provides various guidelines to write the readable in Python. PEP 8 describes how the developer can write beautiful code. It was officially written in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan. The main aim of PEP is to enhance the readability and consistency of code.
The Python standard library is conservative and requires limiting lines to 79 characters (and docstrings/comments to 72). The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces.
You can move your string outside the loop, and then format it before printing, like this:
message = 'Thank you for using our Library! You have decided to borrow {0.title} \
on {0.start_date}. Please remember to return the book in \
{0.lend_duration} calendar days on {0.return_date}'
for i in books:
print(message.format(i))
As it's not mentioned in any other answer, you can use parenenthesis without using +
or \
:
>>> ("hello"
" world")
'hello world'
Combined with Burhan's answer that gives you:
message = ('Thank you for using our Library! You have decided to borrow'
' {0.title} on {0.start_date}. Please remember to return the'
' book in {0.lend_duration} calendar days on {0.return_date}')
for b in books:
print(message.format(b))
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