Use of str() in print()

Asked by At

If I use:

>>> n = input("What is your name? ")
What is your name? 23

>>> print("Hello " + n)

The Output is

Hello 23

Then it prints correctly. But if I use:

>>> n = 1
>>> print("Hello" + n)

Result:

Traceback (most recent call last):   File "<pyshell#74>", line 1, in
<module>
    print("Hello" + n) TypeError: can only concatenate str (not "int") to str

Then it gives an error. I know that it is not allowed to print numbers with string without using the str() function, so in the first case why does it not give an error?

4 Answers

3
Fukiyel On Best Solutions

Because input() always returns a str.

In your first example, n is "23", not 23, so the concatenation works.

3
blhsing On

The input function always returns a string, so even if the user inputs a number, input still returns the number in a string, and therefore it can be concatenated with another string.

0
rkatkam On

The action of operator + depends on the type of operands, but both need to be of same type. For strings, it is meant for concatenations, and hence both the operands are expected of same type string. However, python still lets you print two different type of operands on same line using ,.

For example,

print("Hello ",n)

1
Pierre D On

That's because input() returns a string, i.e., in your example, the string '23'.

Check:

>>> n = input("What is your name? ")
What is your name? 23

>>> print(type(n))
<class 'str'>