1

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

Nander Speerstra
  • 1,496
  • 6
  • 24
  • 29
Dhar Dibya
  • 47
  • 1
  • 10

4 Answers4

2

From the documentation:

All non-keyword arguments are converted to strings like str() does

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

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.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
1
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.

kiner_shah
  • 3,939
  • 7
  • 23
  • 37
0

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
Chidozie Nnachor
  • 872
  • 10
  • 21