Python 格式化可选文本字符串的更有效方法
我已经编写了这段代码:Python 格式化可选文本字符串的更有效方法,python,python-3.x,formatting,Python,Python 3.x,Formatting,我已经编写了这段代码: @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 ''
@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 ''
我想知道是否有一种更干净、更具python风格的方式可以在一行中格式化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生成器,它依赖于一个元素列表,这些元素将被插入到受斜杠限制的字符串中,以减少代码的长度,或者至少使其可重用
您对提高代码的效率/可伸缩性有何建议?您正在组合的令牌的规则性建议了一种基于
加入的方法:
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]) + '/'
IMHOif document_subtype:verification_base+='{0}/'.格式(document_subtype)
更像python.@georgexsh请检查我的编辑。我的函数现在更大了,尝试构建一些更具python风格的东西可能更有意义。你是个黑客。我写了一些类似于zip和join的东西,但还没写好。非常感谢你,我的代码是:def url\u builder(struct):string='/'。join([string if condition else''表示string,condition in zip(*struct)])
I see:)不过请注意,多写几行并显式没有什么问题。对于私人事务,我会选择感觉最满意的,在工作中,我会选择任何我的同事在维护它时不会把我的头扯下来的东西:D这肯定是几个if块,而不是三元运算符。请注意,三元a+b if c else D
:(D,a+b)[c]
;)