Print string and integer in python

前端 未结 1 588
栀梦
栀梦 2021-01-29 16:35

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?

相关标签:
1条回答
  • 2021-01-29 17:31

    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.

    0 讨论(0)
提交回复
热议问题