问题
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
回答1:
displayname = firstname + lastname or username
will work if firstname and last name has 0 length blank string
回答2:
displayname = firstname+' '+lastname if firstname and lastname else username
回答3:
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
回答4:
Ok, I'm assuming you meant __unicode__()
method. Try something like this (not tested, but real close to being correct):
from django.utils.encoding import smart_unicode
def __unicode__(self):
u = self.user
if u.firstname and u.lastname:
return u"%s %s" % (u.firstname, u.lastname)
return smart_unicode(u.username)
I just realized you asked for the Python idiom, not the Django code. Oh well.
回答5:
Something like:
name = data.Name or "Default Name"
回答6:
My schema would have None
as an unset first- or lastname, so Frederico's answer wouldn't work. So:
print ("%s %s" % (firstname, lastname)
if not (firstname and lastname)
else username )
来源:https://stackoverflow.com/questions/1956249/python-idiom-to-check-if-string-is-empty-print-default