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

时间:2017-12-25 18:52:49

标签: python python-3.x formatting

我写了这段代码:

a_p

我想知道是否有一种更清晰,更Pythonic的格式化URL路径的方法只需一行。我最初有:

@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 ''

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

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

修改

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

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

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

您有什么建议来提高代码的效率/可伸缩性?

1 个答案:

答案 0 :(得分:2)

您合并的令牌的规律性表明基于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]) + '/'