What is the difference between "+" and "," when printing?

Question:

What is the difference between these two pieces of code?

name = input("What is your name?")
print("Hello " + name)
name = input("What is your name?")
print("Hello ", name)

I’m sorry if this question seems stupid; I’ve tried looking on Google but couldn’t find an answer that quite answered my question.

Asked By: Winton

||

Answers:

In this example, you have to add an extra whitespace after Hello.

name = input("What is your name?")
print("Hello " + name)

In this example, you don’t have to add an extra whitespace (remove it). Python automatically adds a whitespace when you use comma here.

name = input("What is your name?")
print("Hello ", name)
Answered By: bahrep
print('a'+'b')

Result: ab

The above code performs string concatenation. No space!

print('a','b')

Result: a b

The above code combines strings for output. By separating strings by comma, print() will output each string separated by a space by default.

Answered By: YKWAN

According to the print documentation:

print(*objects, sep=' ', end='n', file=None, flush=False)

Print objects to the text stream file, separated by sep and followed by end.

The default separator between *objects (the arguments) is a space.

For string concatenation, strings act like a list of characters. Adding two lists together just puts the second list after the first list.

Answered By: Thomas Weller

print() function definiton is here: docs

print(*objects, sep=' ', end='n', file=None, flush=False)

Better to explain everything via code

    name = "json singh"

    # All non-keyword arguments are converted to strings like str() does 
    # and written to the stream, separated by sep (which is ' ' by default) 
    # These are separated as two separated inputs joined by `sep` 
    print("Hello", name)
    # Output: Hello json singh 

    # When `sep` is specified like below
    print("Hello", name , sep=',')
    # Output: Hello,json singh
    # However the function below evaluates the output before printing it
    print("Hello" + name)
    # Output: Hellojson singh

    # Which is similar to:
    output = "Hello" + name 
    print(output)
    # Output: Hellojson singh

    # Bonus: it'll evaluate the input so the result will be 5
    print(2 + 3)
    # Output: 5
Answered By: json singh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.