Is there a way to compute the result of len(str(x))
and/or len(repr(x))
without first computing str(x)
or repr(x)
? How?
I may wish to conditionally print an object based on its printed length, so I don't need str(x)
or repr(x)
if I'm not going print it out.
# How might we redefine lenstr so that str(x) need not be computed?
def lenstr(x):
return len(str(x))
def maybe_str(x, maxlen=80, subst='*'):
return subst * maxlen if lenstr(x) > maxlen else str(x)
maybe_str(tuple(range(9)))
# '(0, 1, 2, 3, 4, 5, 6, 7, 8)'
maybe_str(tuple(range(99)))
# '********************************************************************************'
maybe_str(tuple(map(lambda k: tuple(range(k)), range(4))))
# '((), (0,), (0, 1), (0, 1, 2))'
maybe_str(tuple(map(lambda k: tuple(range(k)), range(42))))
'********************************************************************************'