将Python字符串插值拆分为多行
我有一个日志记录语句,类似于:将Python字符串插值拆分为多行,python,pep8,Python,Pep8,我有一个日志记录语句,类似于: get_logger().info( 'Logger logging %s because we need to log it.' % response['foo']['bar'] ) 有了缩进,它就有80多行了。如果我能把它分成%,那就好了 如何将其拆分为多行。(理想情况下,无需将响应['foo']['bar']放入变量)使用Python字符串格式功能时,您可以提供一个元组,而不仅仅是一个值作为输入: >>> "%d %d %d" %
get_logger().info(
'Logger logging %s because we need to log it.' % response['foo']['bar']
)
有了缩进,它就有80多行了。如果我能把它分成%
,那就好了
如何将其拆分为多行。(理想情况下,无需将
响应['foo']['bar']
放入变量)使用Python字符串格式功能时,您可以提供一个元组,而不仅仅是一个值作为输入:
>>> "%d %d %d" % tuple(range(3)) # or just (0, 1, 2)
'0 1 2'
然后轻松地将输入元组拆分为多行。此外,您甚至可以将带有百分比后缀占位符的模板字符串分配给变量,并在以后使用它。例如:
>>> template = "The averaged temperatures of the last three days were %d, %d and %d"
>>> template % (22, 26, 23)
'The averaged temperatures of the last three days were 22, 26 and 23'
您可以在(Python 3.5.4)中了解有关Python字符串格式的更多信息。值得注意的是,对于日志记录
get_logger().info(
'Logger logging %s because we need to log it.'
% response['foo']['bar']
)
同:
get_logger().info(
'Logger logging %s because we need to log it.',
response['foo']['bar']
)
由于debug()
,info()
等。方法将*args
解释为用于对消息进行字符串格式化
通常,对于长字符串(应该环绕第80列的字符串),使用括号,利用python内置的字符串连接:
deeplyNested = True
thing = 'feedback'
class Contrived(object):
def __init__(self):
if deeplyNested:
logger.info(
("Sometimes there's a lot to say in %s and you need to write"
" longer messages than what nicely fits in the 80 column"
" limit."),
thing
)
在%
后面放一个(
在%
后面-把东西放在下一行,然后添加一个)
?谢谢,我想这应该是显而易见的,但我对Python还是相当陌生的。
deeplyNested = True
thing = 'feedback'
class Contrived(object):
def __init__(self):
if deeplyNested:
logger.info(
("Sometimes there's a lot to say in %s and you need to write"
" longer messages than what nicely fits in the 80 column"
" limit."),
thing
)