2017-06-05 68 views
0

可能是一個基本的:是否允許在Python中允許多個字符串格式化操作?

我只是試圖做與編碼鍵的第一個元素在字典的重點之一多個操作,進一步分裂它基於一個字符,並與加盟如下另一個字符串:

images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none" 

代碼片段中,我做以上格式:

from django.http import JsonResponse 
from django.views.decorators.http import require_http_methods 
import requests 

@require_http_methods(["GET"]) 
def images_info(request): 
    response = requests.get("http://127.0.0.1:6000/images/json") 
    table = [] 
    images_list = {} 
    for image in response.json(): 
     try: 
      images_list["RepoTag"] = image["RepoTags"][0].encode("utf-8") 
     except TypeError: 
      images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none" 
     images_list["Id"] = image["Id"].encode("utf-8")[7:19] 
     table.append(images_list) 
     images_list = {} 

    return JsonResponse(table,safe=False) 

有人能告訴我是否是正確的在單一行中完成這些操作的方法?或者以其他方式它遵循python標準嗎?

如果不行的話python標準建議在單行左右的任何有限操作

問這個問題的原因是,根據pep-8,字符數不應超過79個字符。

+0

你確定你的意思是 「操作上在字典中的** **的關鍵之一」? – khelwood

+0

如果沒有損壞,請不要修復它。 –

+0

@Shiva [童子軍規則](http://pragmaticcraftsman.com/2011/03/the-boy-scout-rule/):讓營地比你找到的更清潔。 –

回答

3

將幾個字符串操作鏈接在一起沒有任何問題。如果你想保持它的80個字符的行中,只需添加一些括號:

images_list["RepoTag"] = (
    image["RepoDigests"][0].encode("utf-8").split("@")[0] + 
    ":none") 

或使用str.format()提供那些相同的括號:

images_list["RepoTag"] = '{}:none'.format(
    image["RepoDigests"][0].encode("utf-8").split("@")[0]) 

你可以,否則,平凡使用本地變量:

first_digest = image["RepoDigests"][0].encode("utf-8") 
images_list["RepoTag"] = '{}:none'.format(first_digest.split("@")[0]) 
+0

謝謝..我喜歡str.format(),看起來很乾淨 –

-1

要求不要超過79個字符,但我們可以這樣做。

images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + \ 
    ":none" 

OR

images_list["RepoTag"] = \ 
    image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none" 
+1

更推薦使用圓括號而不是斜線。 – Nurjan