Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing in Python without a space

I've found this problem in a few different places but mine is slightly different so I can't really use and apply the answers. I'm doing an exercise on the Fibonacci series and because it's for school I don't want to copy my code, but here's something quite similar.

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

When this is printed it displays "1 2 3" I don't want this, I'd like it to display it as "1,2,3" or "1, 2, 3" I can do this by using an alteration like this

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

My real question is, is there a way to condense those three lines of code into one line because if I put them all together I get an error.

Thank you.

like image 364
DonnellyOverflow Avatar asked Oct 27 '13 19:10

DonnellyOverflow


2 Answers

Use print() function with sep=', ' like this::

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

To do the same thing with an iterable we can use splat operator * to unpack it:

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

help on 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.
like image 61
Ashwini Chaudhary Avatar answered Sep 29 '22 22:09

Ashwini Chaudhary


You can use the Python string format:

print('{0}, {1}, {2}'.format(one, two, three))
like image 20
Saullo G. P. Castro Avatar answered Sep 30 '22 00:09

Saullo G. P. Castro