【问题标题】:python print statement printing a newline despite a comma尽管有逗号,python print 语句仍打印换行符
【发布时间】:2013-07-28 19:52:40
【问题描述】:

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

我有这个

#! /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,

这样打印 o/p:

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

我想知道为什么在打印“This is a line”之后提示会转到换行符? 因为cat filestest 给出了这个:

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

【问题讨论】:

    标签: python


    【解决方案1】:

    这是标准行为,afaik。您可以改用 sys.output.write ,也可以 设置 sys.output.softspace=False 以防止换行。

    更多详情请看这篇文章:http://code.activestate.com/lists/python-list/419182/

    【讨论】:

      【解决方案2】:

      或者你也可以使用:

      #! /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='')
      

      【讨论】:

      • 在处理文件时尽量使用“with”,这样更简洁。
      【解决方案3】:
      from __future__ import print_function
      
      for line in f:
          print(line, end="")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-14
        • 1970-01-01
        • 1970-01-01
        • 2020-08-19
        • 2012-08-20
        • 1970-01-01
        • 2018-02-17
        • 1970-01-01
        相关资源
        最近更新 更多