不带sp的Python打印

2024-06-08 02:29:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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=", ")

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

谢谢你。


Tags: 答案代码地方错误one学校endthree
3条回答

^{}函数与sep=', '一起使用,如下所示:

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

要对iterable执行相同的操作,我们可以使用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.

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

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=",")

您可以使用Python字符串format

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

相关问题 更多 >

    热门问题