拆分 Python 字符串插值成多行
Spliting Python string interpolation onto multiple lines
我有一个日志记录语句,类似于:
get_logger().info(
'Logger logging %s because we need to log it.' % response['foo']['bar']
)
缩进超过 80 行。如果我能把它分成 %
就可以了。
如何将其拆分为多行。 (理想情况下不只是将 response['foo']['bar']
放入变量)
get_logger().info(
'Logger logging %s because we need to log it.'
% response['foo']['bar']
)
使用 Python 字符串格式化功能时,您可以提供 tuple
作为输入,而不仅仅是单个值:
>>> "%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'
您可以在 printf-style String Formatting (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
解释为用于格式化消息的字符串。
https://docs.python.org/2/library/logging.html#logging.Logger.debug
一般来说,对于长字符串,那些应该环绕在第 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
)
我有一个日志记录语句,类似于:
get_logger().info(
'Logger logging %s because we need to log it.' % response['foo']['bar']
)
缩进超过 80 行。如果我能把它分成 %
就可以了。
如何将其拆分为多行。 (理想情况下不只是将 response['foo']['bar']
放入变量)
get_logger().info(
'Logger logging %s because we need to log it.'
% response['foo']['bar']
)
使用 Python 字符串格式化功能时,您可以提供 tuple
作为输入,而不仅仅是单个值:
>>> "%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'
您可以在 printf-style String Formatting (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
解释为用于格式化消息的字符串。
https://docs.python.org/2/library/logging.html#logging.Logger.debug
一般来说,对于长字符串,那些应该环绕在第 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
)