Python 是否允许对字符串格式化进行多次操作?

Are multiple operations for string formatting allowed in 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])

要求不超过79个字符,我们可以做到。

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

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