views:

506

answers:

6

heya,

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

A: 

Something like:

name = data.Name or "Default Name"
Jesse
+2  A: 
displayname = firstname + lastname or username

will work if firstname and last name has 0 length blank string

S.Mark
+2  A: 

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.

Peter Rowell
+5  A: 
displayname = firstname+' '+lastname if firstname and lastname else username
Federico Ramponi
Beat me to it. +1 baby!
jathanism
+1 You answer is kind enough than me :P
S.Mark
I hate concatenating strings with a + -- it's not safe enough, especially for a user-editable field such as first and last names.
shawnr
A: 

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 )
THC4k
+1  A: 

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

shawnr