Concatenate string and int in python 3.4

前端 未结 6 2123
青春惊慌失措
青春惊慌失措 2021-01-06 05:27

I\'m new to Python, so I\'ve been running through my own set of exercises to simply start memorizing basic functions and syntax. I\'m using Pycharm IDE and Python 3.4. I\'ve

6条回答
  •  粉色の甜心
    2021-01-06 06:24

    In Python 3+, print is a function, so it must be called with its arguments between parentheses. So looking at your example:

    print ("Type string: ") + str(123)
    

    It's actually the same as:

    var = print("Type string: ")
    var + str(123)
    

    Since print returns nothing (in Python, this means None), this is the equivalent of:

    None + str(123)
    

    which evidently will give an error.

    That being said about what you tried to do, what you want do to is very easy: pass the print function what you mean to print, which can be done in various ways:

    print ("Type string: " + str(123))
    
    # Using format method to generate a string with the desired contents
    print ("Type string: {}".format(123)) 
    
    # Using Python3's implicit concatenation of its arguments, does not work the same in Python2:
    print ("Type string:", str(123)) # Notice this will insert a space between the parameters
    

提交回复
热议问题