简体   繁体   English

Python io.StringIO最后添加了额外的换行符

[英]Python io.StringIO adding extra newline at the end

It appears that Python's io.StringIO adds an extra newline at the end when I'm calling its getvalue method. 当我调用它的getvalue方法时,Python的io.StringIO似乎在io.StringIO添加了一个额外的换行符。

For the following code: 对于以下代码:

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

What I'm getting is this, with an extra newline in the end: 我得到的是这个,最后有一个额外的换行符:

1
2
3
4
5

I checked the output with a hex editor, and I'm sure there's an extra newline. 我用十六进制编辑器检查了输出,我确定还有一个额外的换行符。

The document says that: 文件说:

The newline argument works like that of TextIOWrapper. newline参数的工作方式与TextIOWrapper类似。 The default is to consider only \\n characters as ends of lines and to do no newline translation . 默认情况下,只考虑\\ n个字符作为行的结尾, 不进行换行 If newline is set to None, newlines are written as \\n on all platforms, but universal newline decoding is still performed when reading. 如果newline设置为None,则在所有平台上将换行符写为\\ n,但在读取时仍会执行通用换行解码。

And I don't recall the write method append newlines per call. 我不记得write方法每次调用附加换行符。

So why is it adding newlines? 那么为什么要添加换行符呢? I'm writing a script so I would like to make sure that it's behavior is consistent. 我正在写一个脚本,所以我想确保它的行为是一致的。

StringIO isn't doing this, it's print . StringIO不是这样做的,它是print

print prints all its arguments, seperated by sep (by default a space), and ending with end , by default a newline. print打印所有参数,由sep分隔(默认为空格),以end ,默认为换行符。 You can suppress that by doing: 你可以通过这样做来抑制它:

print(res, end="")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM