[Tutor] build list of non-empty variables

Don Jennings dfjennings at gmail.com
Wed Jul 9 00:35:45 CEST 2008


("Duh! Code would be good," says newbie to himself.)

Here's an example from django which I am using, but I asked on this list
since it seems more related to python than the web framework:

class Contact(models.Model):
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    email = models.EmailField(blank=True)
    phone = models.PhoneNumberField()

    def __unicode__(self):
        l=[self.first_name, self.last_name, self.email, self.phone]
        res=[]

        for x in l:
            if x != '':
                res.append(x)

        return ';'.join(res)

Thanks!
Don


On Tue, Jul 8, 2008 at 11:56 AM, Kent Johnson <kent37 at tds.net> wrote:

> On Tue, Jul 8, 2008 at 9:14 AM, Don Jennings <dfjennings at gmail.com> wrote:
> > Hi, folks.
> >
> > From within a class, I want to return a string with data from non-empty
> > variables in a class.
> >
> > I could create a list of all the variables and then iterate over them,
> > dropping the ones which are empty, then join() and return them; however,
> I
> > am guessing there is another way to get that list of variables or to
> > accomplish my goal. Suggestions?
>
> It would help to see code that works according to your suggestion.
>
> Where do the variables come from? Do you mean a list of all the
> attributes in an instance of a class? A list comprehension is often
> useful for creating a filtered list but I don't know if it will work
> for you without understanding better what you want to do.
>
> Kent
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080708/cb1a7113/attachment.htm>


More information about the Tutor mailing list