gpt4 book ai didi

python - 格式化可选文本字符串的更有效方法

转载 作者:行者123 更新时间:2023-12-01 02:20:43 25 4
gpt4 key购买 nike

我写了这段代码:

@staticmethod
def __ver_upload_url(document_type, document_subtype=None):

verification_base = 'verification/{0}/'.format(document_type)
verification_base += '{0}/'.format(document_subtype) if document_subtype is not None else ''

我想知道是否有一种更干净、更 Pythonic 的方法可以在一行中格式化 URL 路径。我最初有:

verification_base = 'verification/{0}/{1}'.format(document_type, document_subtype) \
if document_subtype is not None else 'verification/{0}/'.format(document_type)

我认为它现在更干净、更具可读性,但也许还有更好的方法。

注意:我正在尝试为必须上传的 Django 文件生成路径,并且文件始终具有类型,但并不总是具有子类型(如类别和子类别)。仅当文件具有子类型时,我想添加一个子目录来指定子类型,如果没有,则将其保留在名为该类型的文件夹中。

编辑

我必须升级我的功能,现在它看起来像:

def verification_url(document_type, document_subtype=None, company=False, company_administrator=False):
verification_base = 'verification/'
verification_base += 'companies/' if company or company_administrator else ''
verification_base += 'admins/' if company_administrator else ''
verification_base += '{0}/'.format(document_type)
verification_base += '{0}/'.format(document_subtype) if document_subtype is not None else ''

def function(instance, filename):
id = instance.id if company else instance.user.id
return verification_base + '{user_id}/{filename}'.format(id=id, filename=filename)

我想知道也许我可以编写一个 URL 构建器,它依赖于将插入到由斜杠限制的字符串中的元素列表,以减少代码的长度,或者至少使其可重用。

您对提高代码的效率/可扩展性有什么建议?

最佳答案

您组合的标记的规律性表明采用基于join的方法:

bits = ('verification', 'companies', 'admins', document_type, document_subtype)
flags = (1, company or company_administrator, company_administrator, document_type, document_subtype)

verification_base = '/'.join([b for b, f in zip(bits, flags) if f]) + '/'

关于python - 格式化可选文本字符串的更有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47971235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com