2013-10-27 77 views
4

我在几个不同的地方发现了这个问题,但是我有点不同,所以我不能真正使用和应用答案。 我在斐波纳契系列上做了一个练习,因为它是上学的,我不想复制我的代码,但是这里有一些非常相似的东西。在没有空格的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=", ") 

我真正的问题是做到这一点,是有办法的三行代码凝结成一条线,因为如果我把它们放在一起,我得到一个错误。

谢谢。

+0

'帮助(打印)'可以告诉你... – glglgl

回答

3

您可以使用Python字符串format

print('{0}, {1}, {2}'.format(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=",") 
5

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

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

做同样的事情用一个迭代,我们可以用图示操作*把它解压到:

>>> 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. 
0

你也可以尝试:

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

另一种方式:

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