0

I want to print sum of numbers and some string like:

print("root: " + rootLeaf + " left:" + leftLeaf + "sum: " +(rootLeaf+leftLeaf) )

here "root", "left" and "sum" is string where as rootLeaf and leftleaf are integers and i want to find their sum.

I checked the post here but i couldn't achieve the sum of the integers (math operation in string concatination)

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
abidinberkay
  • 1,857
  • 4
  • 36
  • 68
  • [Format String Syntax](https://docs.python.org/3/library/string.html#format-string-syntax). [Formatted string literals](https://docs.python.org/3/reference/lexical_analysis.html#f-strings) – wwii May 27 '18 at 00:54

4 Answers4

5
rootLeaf = 4
leftLeaf = 8
print("root: " + str(rootLeaf)+ " left: " + str(leftLeaf) + " sum: {}".format(rootLeaf + leftLeaf))

Here is your output:

root: 4 left: 8 sum: 12

In Python, in order to print integers, they must first be converted to strings. The .format method allows you to convert the integer argument (the sum of the two leafs) to strings. You enter a place holder where you want the string {}, and then in your .format method you can specify what that integer will be. In this case, rootLeaf + leftLeaf.

Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27
  • Why not take your use of `format` even further and use that instead of `str(rootLeaf)` and `str(leftLeaf)`? – CodeSurgeon May 27 '18 at 00:30
  • @CodeSurgeon You can if you want to. I wanted to simply introduce the .format() method in this example, but you can do that for all of the integer values as you know. Good point. – Simeon Ikudabo May 27 '18 at 00:32
1

If you are using Python 3, you can try using .format:


print("root: {0} left: {1} sum: {2}".format(rootLeaf, leftLeaf, rootLeaf+leftLeaf))

Or:


print("root: {}".format(rootLeaf), "left: {}".format(leftLeaf) , "sum: {}".format(rootLeaf+leftLeaf))

For older version of Python, you can try using %:


# '+' can be replaced by comma as well
print("root: %s" % rootLeaf + " left: %s" % leftLeaf + " sum: %s" %(rootLeaf+leftLeaf)) 

Or:


print("root: %s left: %s sum: %s" % (rootLeaf, leftLeaf, rootLeaf+leftLeaf))
niraj
  • 17,498
  • 4
  • 33
  • 48
0

Using format should handle all types easily.

print("root: {} left: {} sum: {}".format(rootLeaf, rootRight, rootLeaf + rootRight))

And in general, look in this site for many more details: https://pyformat.info/

ronhash
  • 854
  • 7
  • 16
0

You are getting a TypeError because you are concatenating a string with integers. You need first to convert the integers to strings. You can do this using the str function.

In this case

print("root: " + str(rootLeaf) + " left:" + str(leftLeaf) + "sum: " +str(rootLeaf+leftLeaf))

will print what you want.