6

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.

bryan.blackbee
  • 1,934
  • 4
  • 32
  • 46

3 Answers3

4

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))
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • can i use parenthesis surrounding the strings, and then use `+` instead of backslashes? @burhan-khalid – bryan.blackbee Jun 09 '16 at 05:30
  • I find it interesting that an answer for how to conform to PEP8 on long lines suggests using the backslash (`\`) instead of parenthesis to split into long lines, when PEP8 recommends parenthesis instead of the backslash: *The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.* – SethMMorton Jun 09 '16 at 06:01
  • One reason I use `\\` is that it also works on the REPL. – Burhan Khalid Jun 09 '16 at 06:35
  • @bryanblackbee You don't actually need the `+`s inside of parentheses: `('a' 's' 'd' 'f')` evaluates to `'asdf'`. – reynoldsnlp Oct 30 '19 at 18:42
4

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))
Community
  • 1
  • 1
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
1

Enter a new line like so. see also: Is it possible to break a long line to multiple lines in Python

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"))
Community
  • 1
  • 1
Salailah
  • 435
  • 7
  • 12