【问题标题】:Avoid spurious space in print [duplicate]避免打印中的虚假空间[重复]
【发布时间】:2013-01-09 08:13:58
【问题描述】:

我没想到,但是:

print "AAAA",
print "BBBB"

将输出:

AAAA BBBB

中间有一个额外的空间。这实际上是documented

我怎样才能避免那个多余的空间?文档说:

In some cases it may be functional to write an empty string to standard output for this reason.

但我不知道该怎么做。

【问题讨论】:

    标签: python printing


    【解决方案1】:

    习惯于使用print() 函数而不是语句。它更灵活。

    from __future__ import print_function
    
    print('foo', end='')
    print('bar')
    

    【讨论】:

    • 这确实意味着在这种情况下导入该模块的任何模块都需要修改所有 print 语句
    【解决方案2】:

    三个选项:

    • 不要使用两个打印语句,而是连接值:

      print "AAAA" + "BBBB"
      
    • 使用sys.stdout.write() 直接编写您的语句,而不是使用print 语句

      import sys
      
      sys.stdout.write("AAAA")
      sys.stdout.write("BBBB\n")
      
    • 使用forward-compatible new print() function

      from __future__ import print_function
      
      print("AAAA", end='')
      print("BBBB")
      

    【讨论】:

    • 谢谢!这三个对我来说都是不好的选择:)但我想没有好的选择。我希望 print 语句有一些标志(类似于最终的 ,),但我发现没有办法告诉 print “不要放空格”。
    • @gonvaled:这就是 Python 3 切换到 print() 函数的原因之一;允许您实际更改默认值。添加了 from __future__ 导入以帮助从 2 过渡到 3。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 2015-07-01
    相关资源
    最近更新 更多