principal-ideal-domain
principal-ideal-domain

Reputation: 4266

Concatenate string with number

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

Upvotes: 0

Views: 2289

Answers (1)

Lars Fischer
Lars Fischer

Reputation: 10129

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

Upvotes: 2

Related Questions