2017-01-19 25 views
1

我有一個非常簡單的問題,我一直無法找到解決方案,所以我想我會在這裏嘗試我的「運氣」。如何在遵循pylint規則的同時格式化長字符串?

我有一個字符串是完全使用變量和靜態文本創建的。這是因爲如下:

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

但我的問題是,pylint的抱怨這個字符串reprensentation因爲實在是太長了。這是問題。我如何將這個字符串表示形式化爲多行,而不會看起來很奇怪,仍然保持在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.

回答

3

請勿使用太多的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)) 
+0

感謝您澄清!我不知道你可以使用括號來表示字符串。 我已經知道字符串格式。我已經在我的代碼中多次使用它。此外,我不知道你可以省略字符串格式的數字,例如' 「some_string {0}」。格式(通)'。我想上面的共享代碼只是我學習之前的一個剩餘部分,出於某種原因,我沒有想到是否。大聲笑。 – Zeliax

相關問題