Python获取打印字符串的长度

时间:2017-09-21 02:19:59

标签: python-3.x

假设我有打印功能的args和kwargs,有没有办法获得打印字符串的长度?

e.g。

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

1 个答案:

答案 0 :(得分:1)

您可以使用StringIO执行此操作,并将标准输出捕获为字符串。

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)))

请注意,发送到标准输出的所有内容都将在结果变量中捕获,直到您恢复stdout。