Question

I have following code dealing with printing the output of two lists as string, eventually if the list is empty it should print "EMPTY". It works, but I would like make it somehow shorter.

new = [0,1,3]
old = [0,1,2,3,4,5]
'to: %s from: %s' % (','.join(map(str,new if len(new) > 0 else ["EMPTY"])),','.join(map(str,old if len(old) > 0 else ["EMPTY"])))
#'to: 0,1,3 from: 0,1,2,3,4,5'

Any suggestion will be apriciated.

Assumptions:

  • I have to do it without .format

UPDATE:

So far I managed to do it this way:

'to: %s from: %s' % tuple(','.join(map(str,i if i else ["EMPTY"])) for i in (new, old))
Was it helpful?

Solution 4

Are you actually using print (so you can print a list) or do you need to generate the string?

>>> print "to:", new or "EMPTY" , "from:" , old or "EMPTY"
to: [1, 2, 3] from: [0, 1, 2, 3, 4, 5]
>>> new = []
>>> print "to:", new or "EMPTY" , "from:" , old or "EMPTY"
to: EMPTY from: [0, 1, 2, 3, 4, 5]

OTHER TIPS

To make this readable I'd just factor out the formatting into a function:

def fmt(l):
   return ','.join(map(str, l)) if l else 'EMPTY'

print 'to: %s from: %s' % (fmt(new), fmt(old))
pretty = lambda a: ','.join(map(str, a)) or 'EMPTY'
'to: %s from: %s' % (pretty(old), pretty(new))

You could just do:

"to: {0} from: {1}".format(str(new)[1:-1] if new else "EMPTY", 
                           str(old)[1:-1] if old else "EMPTY")

All empty containers, including [], evaluate False, so you don't need to explicitly check the len(). str() will convert the list to a string (e.g. "[1, 2, 3]") then the slice [1:-1] takes all but the first character ('[') and the last (']').

You can do the same thing with %, but it is deprecated:

"to: %s from: %s" % (str(new)[1:-1] if new else "EMPTY", 
                     str(old)[1:-1] if old else "EMPTY")

Note: this uses Python's default list display, which puts spaces after the commas. If you really can't live with that, you could do:

"to: %s from: %s" % (str(new)[1:-1].replace(" ", "") if new else "EMPTY", 
                     str(old)[1:-1].replace(" ", "") if old else "EMPTY")

Let's see, you can drop the len() calls on both of them, though honestly I'd probably just refactor.

new = [0,1,3] or ["EMPTY"]
old = [0,1,3] or ["EMPTY"]
print "to: %s from: %s" % (','.join(map(str,new)), ','.join(map(str,old)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top