Printing in Python without a space

16,065

Solution 1

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.

Solution 2

You can do this with or without a comma:

1) No spaces

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

2) Comma with space

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

3) Comma without space

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

Solution 3

You can use the Python string format:

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

Solution 4

Another way:

one=1
two=2
three=3
print(', '.join(str(t) for t in (one,two,three)))
# 1, 2, 3
Share:
16,065
DonnellyOverflow
Author by

DonnellyOverflow

Updated on June 11, 2022

Comments

  • DonnellyOverflow
    DonnellyOverflow almost 2 years

    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.