Pythonio.StringIO公司在末尾添加额外的换行符

2024-04-25 23:59:54 发布

您现在位置:Python中文网/ 问答频道 /正文

似乎Python的io.StringIO在调用其getvalue方法时在末尾添加了一个额外的换行符。你知道吗

对于以下代码:

import io
s = io.StringIO()
s.write("1\n2\n3\n4\n5\n")
res = s.getvalue()
s.close()
print(res)

我得到的是这个,结尾有一个额外的新词:

1
2
3
4
5

我用一个十六进制编辑器检查了输出,我确信有一个额外的换行符。你知道吗

这个document说:

The newline argument works like that of TextIOWrapper. The default is to consider only \n characters as ends of lines and to do no newline translation. If newline is set to None, newlines are written as \n on all platforms, but universal newline decoding is still performed when reading.

我不记得每次调用都附加换行符的write方法。你知道吗

那为什么要添加新词呢?我正在写一个脚本,所以我想确保它的行为是一致的。你知道吗


Tags: oftheto方法代码ioisas
1条回答
网友
1楼 · 发布于 2024-04-25 23:59:54

StringIO没有这样做,而是print。你知道吗

print打印它的所有参数,以sep(默认为空格)分隔,以end结尾,默认为换行符。您可以通过执行以下操作来抑制这种情况:

print(res, end="")

相关问题 更多 >