python - Print nothing when number is None -
this script
def p(t, n): if n == none: print "%s" % t else: print "%-10s %3d" % (t, n) p('a' , 4) p('bc' , 12) p('defgh', 876) p('ijk' ,none)
prints
a 4 bc 12 defgh 876 ijk
when executed. can function p
shortened output stays same?
i had hoped define p
as
def p(t, n): print "%-10s %3d" % (t, n)
but definition, script errors "typeerror: %d format: number required, not nonetype".
def p(t, n): print "%-10s %3d" % (t, n) if n else "%s" % t
if want print n if n = 0
print "%-10s %3d" % (t, n) if n not none else "%s" % t
if have multiple args can filter out none values , use str.format.
def p(t, *args): args = filter(none, args) print t,("{} "*len(args)).format(*args)
which outputs:
in [2]: p('defgh', 876, none, 33,none,100) defgh 876 33 100
or replace none values space:
def p(t, *args): print t,("{} "*len(args)).format(*[arg if arg else " " arg in args])
which outputs:
in [4]: p('defgh', 876, none, 33,none,100) defgh 876 33 100
Comments
Post a Comment