在Python中无空格打印
我在几个不同的地方发现了这个问题,但我的问题略有不同,所以我不能真正使用和应用答案。 我正在做一个关于斐波那契级数的练习,因为这是为了上学,我不想复制我的代码,但这里有一个非常类似的东西在Python中无空格打印,python,string,python-3.x,printing,Python,String,Python 3.x,Printing,我在几个不同的地方发现了这个问题,但我的问题略有不同,所以我不能真正使用和应用答案。 我正在做一个关于斐波那契级数的练习,因为这是为了上学,我不想复制我的代码,但这里有一个非常类似的东西 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="
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=", ")
我真正的问题是,有没有办法把这三行代码压缩成一行,因为如果我把它们放在一起,我会得到一个错误
谢谢。您可以使用Python字符串
格式
:
print('{0}, {1}, {2}'.format(one, two, three))
可以使用逗号或不使用逗号执行此操作: 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=",")
one=1
two=2
three=3
print(one, two, three, sep=",")
将函数与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(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.
您也可以尝试:
print("%d,%d,%d"%(one, two, three))
另一种方式:
one=1
two=2
three=3
print(', '.join(str(t) for t in (one,two,three)))
# 1, 2, 3
无空格逗号
one=1
two=2
three=3
print(one, two, three, sep=",")
one=1
two=2
three=3
print(one, two, three, sep=",")
帮助(打印)
本可以告诉你。。。