0

I'd like to concatenate a string with a number to have a nicer output. Unfortunately, this doesn't work.

print "The result is "+x
principal-ideal-domain
  • 3,998
  • 8
  • 36
  • 73
  • 1
    Possible duplicate of [Python: TypeError: cannot concatenate 'str' and 'int' objects](http://stackoverflow.com/questions/11844072/python-typeerror-cannot-concatenate-str-and-int-objects) – KPrince36 Oct 16 '15 at 19:18
  • @KPrince36 Thank you. So instead of a "+" I should use a ",". But why does sage add an additional blank in the printed string? – principal-ideal-domain Oct 16 '15 at 19:23

1 Answers1

2

You have got several options:

  • print "The result is " + str(x)
  • print "The result is", x
  • print "The result is %d"%(x)
  • print "The result is {}".format(x)

Your example with the + operator does not work as you expected, because it needs two string arguments. Your second argument is of type int. You have to convert it to string with the str(x) function. The last two examples are the "old" and "new" way of string formating, see PyFormat.info.

Next to your question in the comment above: why does print "The result is ", x add another space? Thats is how the print keyword works. If it is given a list of expressions. It adds a space between each item of the given list. The first item (the string) has a trailing space. print adds another space, then prints out the second item which is your int. Just try this (without the trailing space in the string): print "The result is", x

Lars Fischer
  • 9,135
  • 3
  • 26
  • 35