Why doesn’t Python automatically convert the number to a string?

Question

Why doesn’t Python automatically convert the number to a string?

Answer

The answer becomes more clear as you learn to debug larger projects, and was carefully thought out when the language was being designed. In Python, and many other languages, the belief is that explicit is better than implicit. This means you should write your code with explicit functionality because by doing so, errors produced will help you understand where you went wrong.
For example, if we don’t convert a number to a string before concatenating it with a string, it gives a specific error that we are accustomed to looking for. However, if Python did this conversion automatically and, somehow, there was a bug in our program, it wouldn’t throw an error message because it converted as the language intended behind the scenes, but produced some unexpected output.

11 Likes

hi
is using quotations the same as using the str() , or are there any differences?

2 Likes

Using quotes is how we define a string. The str() function is for casting a non-string to a string.

str(42)            # '42'

str(True)          # 'True'

str([1,2,3,4,5])   # '[1, 2, 3, 4, 5]'

str({'one': 1})    # "{'one': 1}"

Eg.

def digit_sum(n):
    total = 0
    for x in str(n)
        total += int(x)
    return total

When n is 12345, str(n) will be ‘12345’, an iterable.

2 Likes

This doesn’t makes exact sense considering Python supports implicit Data type conversion!

1 Like

In the context of for Python cannot implicitly create an iterable from an integer. Integers cannot be split.

Hi mtf,

My comment was for this particular answer:
“The answer becomes more clear as you learn to debug larger projects, and was carefully thought out when the language was being designed. In Python, and many other languages, the belief is that explicit is better than implicit. This means you should write your code with explicit functionality because by doing so, errors produced will help you understand where you went wrong.”

If errors occur in an explicit, declarative environment, they occur for a specific reason. Loosely typed environments need tight reins, aka, nearly explicit. They must be able to safely morph one type to another in a meaningful way. We are still in charge of providing that meaning.

There can be no question as to the value of explicitness. What is, is. Implicitness is rife with gray area that needs to be thought over.

JavaScript arrow functions, and Ruby methods share one thing in common… Implicit return.

const f = x => x ** 2;
 >  const f = x => x ** 2
>- undefined
 > f(2)
<- 4
 > f(3)
<- 9
 > f(4)
<- 16

I guess I understand what you are trying to say. However, your answer will make sense only to a seasoned programer who is trying to pick up Python as a new laguage; like me.

For a newbie, it doesnt makes much sense. Also, without going in with a bit detailed explanation it sounds wrong to say that Python expects the Programmer to do explicit data casting for functions & operators which is not really the case since you can add a float & integer to get a float in python unlike some other languages.

What ever I say is refutable. That is stipulated. Discussion should emerge and then form a web. I’ve not got stuck to that yet, but hey, stuff happens.

I like explicit having worked with implicit languages like 4GLs but it is still confusing to a Python newbie e.g. var = 3 then 3 is a string but string + 2 + string gives an error unless I put in str(2) …which implies that the interpreter assumed the 2 was an integer!

if i do:

var = 3
print type(var)

we can clearly see it gives integer as response. If you do:

var = "3"
print type(var)

then you have a string

number = 5
print “the number is : %s” % (number)
print "the number is : " + number

in the above snippet,
the line 2 gets executed successfully, but the line 3 throws an error. So this means Python implicitly converts the number to string in the second line right ?

If you mean,

>>> n = 5
>>> print ("Number = %s" % n)
Number = 5
>>> n = 5.2
>>> print ("Number = %s" % n)
Number = 5.2
>>> 

then, yes, it must be cast to string. Since there is no concatenation (only interpolation) we don’t have to explicity convert it as we would in the latter case. Much as the .format() method does…

>>> print ("Number = {}".format(n))
Number = 5.2
>>> 

By rights, though, we should still tell the template what type to expect, %d, %i or %f. It tells the reader, as well what types are referenced by the variables.

1 Like

Why does str() not change variables into a string? For example when I put:

variable = "some text"

print str(variable)

Why is the output on the console “some text” instead of “variable”?

variable is only a label, not a value. It references a string object, so when we print the variable, the string it points to is what prints.

1 Like

lets say we want a integer from the user:

user_input = raw_input("enter a integer: ")

but raw_input stores the result as string:

print type(user_input)

so we need to cast to integer:

user_input = int(user_input)

if this casting would cast the label/variable, we wouldn’t be able to convert the user input to integer, that wouldn’t be very inconvenient.

I can also use a comma though, is there any reason for why I should use str() or int() etc? instead of a comma?

This

print "The value of pi is around " + str(3.14)

And this

print "The value of pi is around", 3.14

Look exactly the same in the console.

converting/casting data types is used for much more then just this simple print statement.

When I print “The value of pi is around 3.14”, the console prints the exact same thing as when I print "The value of pi is around " + str(3.14).
What’s the purpose of converting 3.14 to a string in this case?

its about the concept, the value might come from user input or a database, then you need to convert to string, you might not always have the luxury to just put the value in the string.