Python简单的first_name last_initial当last_name可以是blan时

2024-04-25 23:56:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在django工作。在

为配置文件模型创建unicode输出,其中user last name是可选的。在

Desired:
  John D. if last name
  John if not last name

Acceptable (though not ideal):
  John . if not last name 

当前代码:

^{pr2}$

这通常可以获得可接受的结果,但当last_name==“”时,此操作将失败。在

有没有一行python习惯用法来生成我想要的输出?我在google和stackoverflow中搜索了六个搜索词,得到了一个鹅蛋。在


Tags: django代码name模型if配置文件unicodenot
3条回答

简单的出路:

def format_name(fname, lname):
    if lname:
        return "{0} {1}.".format(fname, lname)
    return fname

那么只要return format_name(self.user.first_name, self.user.last_name)在你的__unicode__中。这是一行重要的内容(在您的模型中),并且易于引导。在

也许你可以用这样的方法:

def __unicode__(self):
    return "%s%s" % (self.user.first_name,
                     " %s." % self.user.last_name[0]
                       if self.user.last_name
                       else "")

怎么样:

return self.user.first_name + (' %s.' % self.user.last_name[0] if self.user.last_name  else '')

以上是写为一行,因为你已经明确要求。我个人会把它分成两行:

^{pr2}$

相关问题 更多 >

    热门问题