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

Zel*_*iax 2 python string pylint python-3.x

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

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

filename_gps = 'id' + str(trip_id) + '_gps_did' + did + '_start' + str(trip_start) + '_end' + str(trip_end) + '.json'
Run Code Online (Sandbox Code Playgroud)

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

有一次,我最终使它看起来像这样,但是看起来令人难以置信的“丑陋”:

filename_gps = 'id' + str(
    trip_id) + '_gps_did' + did + '_start' + str(
                trip_start) + '_end' + str(
                trip_end) + '.json'
Run Code Online (Sandbox Code Playgroud)

我发现如果我这样格式化它,它会遵循 pylint 的“规则”:

filename_gps = 'id' + str(
    trip_id) + '_gps_did' + did + '_start' + str(
    trip_start) + '_end' + str(
    trip_end) + '.json'
Run Code Online (Sandbox Code Playgroud)

哪个看起来更“漂亮”,但如果我没有“str()”强制转换,我将如何创建这样的字符串?

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

Mar*_*ers 5

不要使用这么多str()电话。使用字符串格式

filename_gps = 'id{}_gps_did{}_start{}_end{}.json'.format(
    trip_id, did, trip_start, trip_end)
Run Code Online (Sandbox Code Playgroud)

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

filename_gps = (
    'id' + str(trip_id) + '_gps_did' + did + '_start' +
    str(trip_start) + '_end' + str(trip_end) + '.json')
Run Code Online (Sandbox Code Playgroud)

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

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))
Run Code Online (Sandbox Code Playgroud)