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.
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.
You can use the Python string format
:
print('{0}, {1}, {2}'.format(one, two, three))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With