符合长行以适应 PEP 8

Conform long lines to fit PEP 8

我对 PEP 8 中的样式有疑问(或减少每行中的字符数)。

假设我有一个 book 具有一堆不同的属性,我想将它们连接成一些字符串。

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"))

如何缩短这一行以确保其可读性?

任何想法都会有所帮助。 PEP 8 只是 1 个想法。

像这样输入一个新行。另见: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"))

您可以将字符串移出循环,然后在打印前对其进行格式化,如下所示:

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))

因为在任何其他答案中都没有提到,您可以使用 +\:

而不用 来使用括号
>>> ("hello"
     " world")
'hello world'

结合 可以得到:

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))