-7

I always wonder why in Python that is supposed to be easy and fast for developing and you don't even specify types, you must cast an integer to string if you want to print it? It is really annoying.

print "some string"+some_int

gives TypeError: cannot concatenate 'str' and 'int' objects

print "some string"+str(some_int)

Is okay.

4
  • 2
    What's the question here? Commented Oct 21, 2015 at 18:01
  • 1
    If some_int is an integer, neither of your codes will work. Did you mean str(some_int) on the second? Commented Oct 21, 2015 at 18:03
  • OP, check your assumptions. You write, "you must cast an integer to string if you want to print it." That is untrue. I print lots of integers, and I don't recall ever casting one to a string. Commented Oct 21, 2015 at 18:10
  • @dandikain: erm, only because you just fixed it. :-) Commented Oct 21, 2015 at 18:32

1 Answer 1

3

1) Because there is not a clear, unambiguous meaning of str+int. Consider:

x = "5" + 7

Should the + str-ify the 7 or int-ify the "5"? One way yields 12, the other yields "57".

2) Because there are other alternatives that more clearly express the programmer's intent:

print "5", 7
print "5%d" % 7
print "5{:d}".format(7)

each of these have a clear meaning, and none of them represent an onerous burden to the programmer.

Aside: I would never use "some string"+str(some_int). String concatenation is a limited case of the more general, easier to use string formatting facilities I listed above.

Sign up to request clarification or add additional context in comments.

1 Comment

x = "5" + 7 may seem ambiguous but does str.__add__(7) seem so? If I was implementing the str class it doesn't seem unreasonable to accept types other than str to use for concatenation and then call __str__() on them. I think the OP has a valid point.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.