6

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

Blair Conrad
  • 233,004
  • 25
  • 132
  • 111
victorhooi
  • 16,775
  • 22
  • 90
  • 113

6 Answers6

6
displayname = firstname+' '+lastname if firstname and lastname else username
Federico A. Ramponi
  • 46,145
  • 29
  • 109
  • 133
  • I hate concatenating strings with a + -- it's not safe enough, especially for a user-editable field such as first and last names. – shawnr Dec 24 '09 at 17:27
4
displayname = firstname + lastname or username

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

YOU
  • 120,166
  • 34
  • 186
  • 219
4

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
  • 883
  • 8
  • 14
2

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
  • 17,605
  • 2
  • 49
  • 65
1

Something like:

name = data.Name or "Default Name"
Jesse Vogt
  • 16,229
  • 16
  • 59
  • 72
0

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 )
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194