繁体   English   中英

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM