是否允许在Python中允许多个字符串格式化操作?
问题描述:
可能是一个基本的:是否允许在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个字符。
答
将几个字符串操作链接在一起没有任何问题。如果你想保持它的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(),看起来很干净 –
答
要求不要超过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
你确定你的意思是 “操作上在字典中的** **的关键之一”? – khelwood
如果没有损坏,请不要修复它。 –
@Shiva [童子军规则](http://pragmaticcraftsman.com/2011/03/the-boy-scout-rule/):让营地比你找到的更清洁。 –