【问题标题】:Printing in Python without a space在没有空格的 Python 中打印
【发布时间】:2013-11-06 11:38:59
【问题描述】:

我在几个不同的地方发现了这个问题,但我的略有不同,所以我不能真正使用和应用答案。 我正在做一个关于斐波那契数列的练习,因为它是为了学校我不想复制我的代码,但这里有一些非常相似的东西。

one=1
two=2
three=3
print(one, two, three)

打印时显示“1 2 3” 我不想要这个,我希望它显示为“1,2,3”或“1,2,3” 我可以通过使用这样的更改来做到这一点

one=1
two=2
three=3
print(one, end=", ")
print(two, end=", ")
print(three, end=", ")

我真正的问题是,有没有办法将这三行代码压缩成一行,因为如果我把它们放在一起就会出错。

谢谢。

【问题讨论】:

  • help(print) 可以告诉你...

标签: python string python-3.x printing


【解决方案1】:

像这样使用print()sep=', ' 函数::

>>> print(one, two, three, sep=', ')
1, 2, 3

要对可迭代对象做同样的事情,我们可以使用 splat 运算符 * 对其进行解包:

>>> print(*range(1, 5), sep=", ")
1, 2, 3, 4
>>> print(*'abcde', sep=", ")
a, b, c, d, e

关于print的帮助:

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

【讨论】:

    【解决方案2】:

    你也可以试试:

    print("%d,%d,%d"%(one, two, three))
    

    【讨论】:

      【解决方案3】:

      您可以使用或不使用逗号来执行此操作:

      1) 没有空格

      one=1
      two=2
      three=3
      print(one, two, three, sep="")
      

      2) 逗号加空格

      one=1
      two=2
      three=3
      print(one, two, three, sep=", ")
      

      3) 逗号没有空格

      one=1
      two=2
      three=3
      print(one, two, three, sep=",")
      

      【讨论】:

        【解决方案4】:

        另一种方式:

        one=1
        two=2
        three=3
        print(', '.join(str(t) for t in (one,two,three)))
        # 1, 2, 3
        

        【讨论】:

          【解决方案5】:

          可以使用 Python 字符串format:

          print('{0}, {1}, {2}'.format(one, two, three))
          

          【讨论】:

            猜你喜欢
            • 2012-09-23
            • 1970-01-01
            • 2021-07-16
            • 2013-03-05
            • 1970-01-01
            • 2016-01-24
            • 2014-03-06
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多