Print Combining Strings and Numbers

PythonPython 2.7

Python Problem Overview


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 number is %(second)d" % {"first": first, "second":second}

Python Solutions


Solution 1 - Python

> 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.

Solution 2 - Python

Yes there is. The preferred syntax is to favor str.format over the deprecated % operator.

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

Solution 3 - Python

if you are using 3.6 try this

 k = 250
 print(f"User pressed the: {k}")

> Output: User pressed the: 250

Solution 4 - Python

The other answers explain how to produce a string formatted like in your example, but if all you need to do is to print that stuff you could simply write:

first = 10
second = 20
print "First number is", first, "and second number is", second

Solution 5 - Python

In Python 3.6

a, b=1, 2 

print ("Value of variable a is: ", a, "and Value of variable b is :", b)

print(f"Value of a is: {a}")

Solution 6 - Python

import random
import string
s=string.digits
def foo(s):
  r=random.choice(s)
  p='('
  p2=')'
  str=f'{p}{r}{p2}'
  print(str)
foo(s)

thank me later

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondarkskyView Question on Stackoverflow
Solution 1 - PythonLevonView Answer on Stackoverflow
Solution 2 - PythonAntimonyView Answer on Stackoverflow
Solution 3 - PythonGeorge C.View Answer on Stackoverflow
Solution 4 - PythonMatteo ItaliaView Answer on Stackoverflow
Solution 5 - PythonGurdeep SinghView Answer on Stackoverflow
Solution 6 - PythonfinnView Answer on Stackoverflow