Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Combining Strings and Numbers

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} 
like image 754
darksky Avatar asked Aug 18 '12 13:08

darksky


People also ask

How do I combine numbers and strings?

To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.

How do you combine variables and strings?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect.

How do I print numbers in a string?

To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.


1 Answers

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.

like image 156
Levon Avatar answered Sep 20 '22 15:09

Levon