具有类似于打印功能签名的格式化功能

时间:2019-03-05 15:34:06

标签: python python-3.x string-formatting

我有一些代码可以使用print函数的某些功能将内容打印到控制台,例如

print('name'.ljust(44), 'age'.rjust(4), 'idea'.rjust(8), sep=',')
for name, age, idea in items:    
    print(name.ljust(44), str(age).rjust(4), idea.rjust(8), sep=',')

在其他情况下,我将使用end参数将多个字符串写入一行,即

print('hello ', end='')
print('world!')

我的问题是,如何才能最轻松地将此print格式的输出写入流,文件,或者甚至最好将其收集到单个字符串对象中?如果我恢复为常规字符串格式,则语法会有所不同,我将需要重新编写所有格式。

2 个答案:

答案 0 :(得分:1)

StringIO允许您将字符串当作文件来使用。与使用print(..., file=...)一起,您可以执行以下操作:

import io

with io.StringIO() as fp:
    print("hi", "mom", sep=" ", file=fp)
    print('hello ', end='', file=fp)
    print('world!', file=fp)

    str = fp.getvalue()

print(str)

给出

hi mom
hello world!

根据您的需求(我认为)。如果您需要每行的字符串列表,也可以使用fp.readlines()

您还可以使用tempfile,它可以使用文件系统(但可以不使用),语法几乎相同:

import tempfile

with tempfile.TemporaryFile(mode="w+") as fp:
    print("hi", "mom", sep=" ", file=fp)
    print('hello ', end='', file=fp)
    print('world!', file=fp)

    fp.seek(0)
    str = fp.read()

print(str)

您确实需要指定mode,因为默认情况下会给出一个二进制文件,该文件不允许您print,并在读之前明确地倒回到开头。 (FWIW,我的答案的较早版本每个flush=True都有print,但我认为这不是必需的。)

答案 1 :(得分:0)

泡菜会帮你吗?

类似

import pickle

text = "Hallo welt          Test."

with open('parrot.pkl', 'wb') as f:
    pickle.dump(text, f)


with open('parrot.pkl', 'rb') as f:
    print(pickle.load(f))
相关问题