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}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With