What is the difference between print(9)
and print(str(9))
in Python when the output is the same for both functions?

- 1,496
- 6
- 24
- 29

- 47
- 1
- 10
-
2What's a difference between `1+4` and `2+3` when output is same for both statements? – Łukasz Rogalski Sep 05 '16 at 06:50
-
If you were wondering why `type(9)` and `type((9))` both give the same answer (`int`) as well: http://stackoverflow.com/questions/12876177/why-do-tuples-with-only-one-element-get-converted-to-strings – StefanS Sep 05 '16 at 06:55
-
@StefanS I think you missed the `str` part from OP’s code. – poke Sep 05 '16 at 06:55
-
Oh yes, I did. Sorry for the confusion. – StefanS Sep 05 '16 at 06:59
4 Answers
From the documentation:
All non-keyword arguments are converted to strings like
str()
does

- 776,304
- 153
- 1,341
- 1,358
print
will always first try to call __str__
on the object you give it. In the first case the __str__
of the int instance 9
is '9'
.
In the second case, you first explicitly call str
on 9
(which calls its __str__
and yields '9'
). Then, print
calls '9'
's __str__
which, if supplied with a string instance, returns it as it is resulting in '9'
again.
So in both cases, in the end print
will print out similar output.

- 150,925
- 31
- 268
- 253
print(str(9))
print(9)
Output:
9
9
There is no change in output. But if we check the data type by executing,
print(type(str(9)))
print(type(9))
Then we get output as,
<class 'str'>
<class 'int'>
So, you can see, the types are different but the output is same.

- 3,939
- 7
- 23
- 37
In simple terms:
An integer is a variable that specifically holds a numerical value. Whereas a string is a variable that can hold a range of characters (including numbers).
print(9) says it should print the NUMERICAL value 9
print(str(9)) says it should print the character 9,
So if you were to do additions on both types for instance:
9 + 9 will always return 18
str(9) + str(9) will always return 99

- 872
- 10
- 21