我对PEP 8中的样式有疑问(或者将每行中的字符数减少到更小)。
考虑到我有一个book
带有一堆不同的属性,我想将它们连接成一些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"))
如何缩短此行以确保其可读性?
任何想法都会有所帮助。 PEP 8只是一个想法。
答案 0 :(得分:4)
您可以将字符串移出循环,然后在打印前对其进行格式化,如下所示:
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))
答案 1 :(得分:3)
由于在任何其他答案中都没有提及,您可以使用parenenthesis 而不使用使用+
或\
:
>>> ("hello"
" world")
'hello world'
与Burhan's answer结合使用:
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))
答案 2 :(得分: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"))
答案 3 :(得分:0)
尝试这种方法:
print(("Thank you for using our Library! You have decided to borrow {} "
+ "on {}. Please remember to return the book in {} calendar days"
+ "on {}").format(book.title, book.start_date, book.lend_duration,
book.return_date)
请注意,字符串连接位于parens内部,允许您格式化结果字符串。