aero
aero

Reputation: 270

How can I count the length of the output of print in Python?

Is there a way to count the length of an output from print in Python?
For example, I want to count the length of the output:

print ("|L|",*L, sep='')

where L is a list.

I am not trying to get the len(L), rather I want to know the length of the output of the print statement above after printing.

Upvotes: 1

Views: 2322

Answers (1)

Arseni Mourzenko
Arseni Mourzenko

Reputation: 52311

You can store the text first in a string:

elements = ['|L |'] + L
text = ''.join(elements)

or if the list contains something other than strings:

elements = ['|L |'] + L
text = ''.join(map(str, elements))

then check the length:

length = len(text)

and finally output the text:

print(text)

Note that you will get the length of the string, not the actual number of characters printed on the screen. For example, ANSI escape sequences which change the color of the console will be included in the length of the string, while they aren't displayed in the console itself.

Upvotes: 2

Related Questions