What is the difference between print(9) and print(str(9)) in Python when the output is the same for both functions?
- 1,438
- 6
- 24
- 28
- 27
- 1
- 9
-
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
- 740,318
- 145
- 1,296
- 1,325
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.
- 136,212
- 29
- 242
- 233
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,445
- 6
- 25
- 36
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
- 744
- 9
- 19