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

时间:2017-01-19 07:49:10

标签: python string python-3.x pylint

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

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

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

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

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

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

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

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

这看起来更“漂亮”,但是如果我没有“str()”演员,我将如何创建这样的字符串?

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

1 个答案:

答案 0 :(得分:4)

请勿使用这么多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))