简体   繁体   English

尽管有逗号,python print语句打印换行符

[英]python print statement printing a newline despite a comma

'2.6.5 (r265:79063, Apr 16 2010, 13:57:41) \\n[GCC 4.4.3]' '2.6.5(r265:79063,2010年4月16日,13:57:41)\\ n [GCC 4.4.3]'

I have this 我有这个

#! /usr/bin/env python

f = open('filetest', 'w')
f.write("This is a line")

f.close()

f = open('filetest', 'r')


for i in f.readlines():
    print i,

This prints the o/p like this: 这打印o / p像这样:

$ ./filetest.py 
This is a line
abc@abc-ubuntu:~/pythonpractice$

I am wondering why does the prompt go to the newline after "This is a line" is printed? 我想知道为什么在打印“This is a line”之后提示符转到换行符? Because cat filestest gives this: 因为cat filestest给出了:

$ cat filetest
This is a lineabc@abc-ubuntu:~/pythonpractice$ 

This is standard behavior, afaik. 这是标准行为,afaik。 You can use sys.output.write instead, or you can set sys.output.softspace=False to prevent the newline. 您可以改为使用sys.output.write,也可以设置sys.output.softspace = False以防止换行。

See this article for more details: http://code.activestate.com/lists/python-list/419182/ 有关更多详细信息,请参阅此文章: http//code.activestate.com/lists/python-list/419182/

OR you can also use: 或者您也可以使用:

#! /usr/bin/env python
from __future__ import print_function

with open('filetest', 'w') as f1:
    f1.write("This is a line")

with open('filetest', 'r') as f2:
    for line in f2.readlines():
        print(line, end='')
from __future__ import print_function

for line in f:
    print(line, end="")

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

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