2 ms·
>>> print "x: "+x Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects To my mind
by jibiki 18y ago
>>> print "x: "+x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
To my mind, "x: "+x is ugly. Perl style "x: $x" makes more sense. But I don't speak python, so my opinion is meaningless.
- mbrubeck 18y agoIt works if you use a comma, like the comment you replied to. Python 2.6 introduces string interpolation like Ruby/Perl. (Older versions used printf-style format strings.) print "x: {x}".format(x=1234) # New in 2.6 print "x: %d" % x # Old http://docs.python.org/tutorial/inputoutput.html#fancier-output-formatting http://docs.python.org/tutorial/inputoutput.html#fancier-out...
- eru 18y agoThis also works: >>> "X: %(x)s" % {"x":10} 'X: 10'
- iclelland 18y agoTo be fair, that's not quite the same as perl/shell-style interpolation. In perl, "$x" pulls the value of $x from the variable namespace. In your Py2.6 example, the "{x}" format in the string has nothing to do with a variable named x; rather it references the keyword args supplied to format. To simulate perl's print "x: $x"; you would print "x: {x}".format(x=x)