0
假設我具有打印功能的參數和kwargs,是否有任何方法可以獲取打印字符串的長度?Python獲取打印字符串的長度
例如
>>> args = [1, 2, 3, 4]
>>> kwargs = {'sep':'<='}
>>> print (*args, **kwargs)
1<=2<=3<=4
>>> printlen (*args, **kwargs)
11
假設我具有打印功能的參數和kwargs,是否有任何方法可以獲取打印字符串的長度?Python獲取打印字符串的長度
例如
>>> args = [1, 2, 3, 4]
>>> kwargs = {'sep':'<='}
>>> print (*args, **kwargs)
1<=2<=3<=4
>>> printlen (*args, **kwargs)
11
您可以使用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爲止。