Python - 检查字符串是否为空的惯用法,打印默认值
我只是想知道,是否有一个Python习惯来检查字符串是否为空,然后如果是则打印默认值?
(上下文是 Django,对于 UserProfile 的 __unicode__(self) 函数 - 基本上,我想打印名字和姓氏(如果存在),然后打印用户名(如果两者都不存在)存在)。
干杯, 胜利者
I'm just wondering, is there a Python idiom to check if a string is empty, and then print a default if it's is?
(The context is Django, for the __unicode__(self)
function for UserProfile - basically, I want to print the first name and last name, if it exists, and then the username if they don't both exist).
Cheers,
Victor
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果名字和姓氏的空白字符串长度为 0,则有效
will work if firstname and last name has 0 length blank string
我认为这个问题最好在模板中处理,例如:
{{ user.get_full_name|default:user.username }}
它使用 Django 包含的“默认”过滤器。如果您特别关心 None 值,但希望允许空白值(即“”),还有一个“default_if_none”过滤器。 “默认”过滤器将在 None 值和 '' 值上触发。
这是 Django 文档的链接:
http://docs.djangoproject.com/en/dev/ref /templates/builtins/#default
I think this issue is better handled in the templates with something like:
{{ user.get_full_name|default:user.username }}
That uses Django's included "default" filter. There is also a "default_if_none" filter if you are specifically concerned about a None value, but want to allow a blank value (i.e. ''). The "default" filter will trigger on both a None value and a '' value.
Here's the link to the Django docs on it:
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#default
好的,我假设您指的是
__unicode__()
方法。尝试这样的事情(未经测试,但非常接近正确):我刚刚意识到你要求的是 Python 惯用法,而不是 Django 代码。那好吧。
Ok, I'm assuming you meant
__unicode__()
method. Try something like this (not tested, but real close to being correct):I just realized you asked for the Python idiom, not the Django code. Oh well.
像这样的东西:
Something like:
我的架构将
None
作为未设置的名字或姓氏,因此 Frederico 的答案不起作用。所以:My schema would have
None
as an unset first- or lastname, so Frederico's answer wouldn't work. So: