Print Combining Strings and Numbers

后端 未结 5 772
野趣味
野趣味 2020-11-28 22:26

To print strings and numbers in Python, is there any other way than doing something like:

first = 10
second = 20
print \"First number is %(first)d and second         


        
5条回答
  •  迷失自我
    2020-11-28 22:55

    Using print function without parentheses works with older versions of Python but is no longer supported on Python3, so you have to put the arguments inside parentheses. However, there are workarounds, as mentioned in the answers to this question. Since the support for Python2 has ended in Jan 1st 2020, the answer has been modified to be compatible with Python3.

    You could do any of these (and there may be other ways):

    (1)  print("First number is {} and second number is {}".format(first, second))
    (1b) print("First number is {first} and number is {second}".format(first=first, second=second)) 
    

    or

    (2) print('First number is', first, 'second number is', second) 
    

    (Note: A space will be automatically added afterwards when separated from a comma)

    or

    (3) print('First number %d and second number is %d' % (first, second))
    

    or

    (4) print('First number is ' + str(first) + ' second number is' + str(second))
      
    

    Using format() (1/1b) is preferred where available.

提交回复
热议问题