H.v.M.
H.v.M.

Reputation: 1633

Print without space in python 3

I'm new to Python, and I'm wondering how to print multiple values without having the extra space added in between. I want the output ab rather than a b without having to call print twice:

print("a", end="")
print("b")

Also, I have the following code:

a = 42
b = 84 

and I want to print their values as a = 42, b = 84, yet if I do

print("a = ", a, ", b = ", b)

extra spaces are added (it outputs a = 42 , b = 84)

Whereas the Java style,

print("a = " + a + ", b = " + b)

raises a TypeError.

Upvotes: 29

Views: 77464

Answers (6)

kavitha
kavitha

Reputation: 11

To separate the strings or values you can use sep parameter in print()

print(a,b,sep='')

Upvotes: 1

aude
aude

Reputation: 1872

print() will automatically make spaces between arguments.

>>> print("a", "b", "c")
a b c

To have more control over spacing, you could use string formatting:

>>> v0, v1, v2 = "a", "b", "c"
>>> print("%s%s%s" % (v0, v1, v2))
abc
>>> print("%s%s%s".format(v0, v1, v2)
abc
>>> print(f"{v0}{v1}{v2}")
abc

I like this guide on the subject: https://realpython.com/python-f-strings/

Upvotes: 0

Siva Prakash
Siva Prakash

Reputation: 4997

The actual syntax of the print() function is

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

You can see it has an arg sep with default value ' '. That's why space gets inserted in between.

print("United","States")            #Output: United States
print("United","States",sep="")     #Output: UnitedStates

Upvotes: 6

DSM
DSM

Reputation: 353019

You can use the sep parameter to get rid of the spaces:

>>> print("a","b","c")
a b c
>>> print("a","b","c",sep="")
abc

I don't know what you mean by "Java style"; in Python you can't add strings to (say) integers that way, although if a and b are strings it'll work. You have several other options, of course:

>>> print("a = ", a, ", b = ", b, sep="") 
a = 2, b = 3
>>> print("a = " + str(a) + ", b = " + str(b))
a = 2, b = 3
>>> print("a = {}, b = {}".format(a,b))
a = 2, b = 3
>>> print(f"a = {a}, b = {b}")
a = 2, b = 3

The last one requires Python 3.6 or later. For earlier versions, you can simulate the same effect (although I don't recommend this in general, it comes in handy sometimes and there's no point pretending otherwise):

>>> print("a = {a}, b = {b}".format(**locals()))
a = 2, b = 3
>>> print("b = {b}, a = {a}".format(**locals()))
b = 3, a = 2

Upvotes: 50

Rishabh Kalakoti
Rishabh Kalakoti

Reputation: 84

You can also use

print("%d%d" %(a,b))

to print a and b not seperated by spaces in form of a formatted string. This is similar to the one in c.

Upvotes: 0

eyelesscactus54
eyelesscactus54

Reputation: 116

On this page the answer is to print your normal text and at the end to use sep="".

So the command

print("Hole", hole, "Par", par, sep="")

will give

"Hole1Par4"

assuming that hole==1 and par==4.

Upvotes: -2

Related Questions