1

Say I have the args and kwargs of a print funtion, is there any way to get the length of the printed string?

e.g.

>>> args = [1, 2, 3, 4]
>>> kwargs = {'sep':'<='}
>>> print (*args, **kwargs)
1<=2<=3<=4
>>> printlen (*args, **kwargs)
11

1 Answer 1

2

You can do this using StringIO and capture standard output as string.

from io import StringIO 
import sys
old_out = sys.stdout # Store stdout to a temp
result = StringIO() # Will capture standard output as string
sys.stdout = result # assign result to sys.stdout
args = [1, 2, 3, 4]
kwargs = {'sep':'<='}
print (*args, **kwargs) # This will be written to result, Not displayed in stdout
sys.stdout = old_out # restore stdout to make things normal
res = result.getvalue()
print ("result: {}, length: {}".format(res, len(res)))

Note that everything that is sent to standard output will be captured in result variable till you restore stdout.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.