无需空格即可在Python中打印

Jam*_*lly 5 python printing string python-3.x

我在几个不同的地方发现了这个问题,但我的情况略有不同,所以我无法真正使用并应用答案.我正在对Fibonacci系列进行练习,因为它是为了学校,我不想复制我的代码,但这里的东西非常相似.

one=1
two=2
three=3
print(one, two, three)
Run Code Online (Sandbox Code Playgroud)

当它被打印时显示"1 2 3"我不想要这个,我希望它显示为"1,2,3"或"1,2,3"我可以通过改变来做到这一点像这样

one=1
two=2
three=3
print(one, end=", ")
print(two, end=", ")
print(three, end=", ")
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Ash*_*ary 5

使用这样的print()功能sep=', '::

>>> print(one, two, three, sep=', ')
1, 2, 3
Run Code Online (Sandbox Code Playgroud)

要使用iterable执行相同的操作*,我们可以使用splat运算符来解压缩它:

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

帮助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.
Run Code Online (Sandbox Code Playgroud)


Sau*_*tro 3

您可以使用 Python 字符串format

print('{0}, {1}, {2}'.format(one, two, three))
Run Code Online (Sandbox Code Playgroud)