【问题标题】:What is the alternate to \n in python? [closed]python中\n的替代方法是什么? [关闭]
【发布时间】:2017-02-05 19:39:47
【问题描述】:

我想在 python 中打印以下输出:

 99 buckets of bits on the bus.
 99 buckets of bits.
 Take one down, short it to ground.
 98 buckets of bits on the bus.

只有一个打印命令,中间没有“\n”字符。如何做到这一点?

【问题讨论】:

  • 如果你想要换行符,你必须把它们放在那里......你怎么能指望程序只是猜测你想要换行符?
  • 您将for i in range(10): print(i) 算作一个打印命令还是十个打印命令?如果您使用三引号字符串文字并且有换行符但它们是隐式的怎么办?
  • 我认为更好的问题是为什么

标签: python newline end-of-line


【解决方案1】:

使用三引号字符串文字,您可以使用实际的换行符代替\n

print(""" 99 buckets of bits on the bus.
 99 buckets of bits.
 Take one down, short it to ground.
 98 buckets of bits on the bus.""")

【讨论】:

    【解决方案2】:
    import os
    print os.linesep.join(["99 buckets of bits on the bus.",
     "99 buckets of bits.",
     "Take one down, short it to ground.",
     "98 buckets of bits on the bus."])
    

    【讨论】:

    • 大声笑,很好的编辑!非常令人印象深刻的跨平台兼容性
    【解决方案3】:

    这似乎有效:

    print chr(10).join([
        '99 buckets of bits on the bus.',
        '99 buckets of bits.',
        'Take one down, short it to ground.',
        '98 buckets of bits on the bus.'
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-16
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      • 2013-10-09
      • 1970-01-01
      • 2015-10-28
      相关资源
      最近更新 更多