如何在遵循 pylint 规则的同时格式化长字符串?

How to format a long string while following pylint rules?

我有一个非常简单的问题,我一直找不到解决方案,所以我想我会在这里尝试 "luck"。

我有一个完全使用变量和静态文本创建的字符串。具体如下:

filename_gps = 'id' + str(trip_id) + '_gps_did' + did + '_start' + str(trip_start) + '_end' + str(trip_end) + '.json'

但是我的问题是 pylint 抱怨这个字符串表示太长了。这就是问题所在。我如何在多行上格式化这个字符串表示而不让它看起来很奇怪并且仍然留在 pylint 的 "rules" 内?

有一次我最终把它变成了这个样子,但是这真是令人难以置信"ugly":

filename_gps = 'id' + str(
    trip_id) + '_gps_did' + did + '_start' + str(
                trip_start) + '_end' + str(
                trip_end) + '.json'

我发现如果我这样格式化它会遵循pylint的"rules":

filename_gps = 'id' + str(
    trip_id) + '_gps_did' + did + '_start' + str(
    trip_start) + '_end' + str(
    trip_end) + '.json'

有很多 "prettier" 值得一看,但如果我没有 "str()" 转换,我将如何创建这样的字符串?

我怀疑 Python 2.x 和 3.x 的 pylint 之间是否存在差异,但如果存在差异,我正在使用 Python 3.x。

不要使用那么多 str() 电话。使用 string formatting:

filename_gps = 'id{}_gps_did{}_start{}_end{}.json'.format(
    trip_id, did, trip_start, trip_end)

如果您确实有一个包含很多部分的长表达式,您可以使用 (...) 括号创建更长的逻辑行:

filename_gps = (
    'id' + str(trip_id) + '_gps_did' + did + '_start' +
    str(trip_start) + '_end' + str(trip_end) + '.json')

这也适用于分解您在格式化操作中用作模板的字符串:

foo_bar = (
    'This is a very long string with some {} formatting placeholders '
    'that is broken across multiple logical lines. Note that there are '
    'no "+" operators used, because Python auto-joins consecutive string '
    'literals.'.format(spam))