When doing string formatting in Python, I noticed that %s transforms also numbers to strings.
>>> a = 1
>>> b = 1.1
>>> c = 'hello'
>>> print 'Integer: %s; Float: %s; String: %s' % (a, b, c)
Integer: 1; Float: 1.1; String: hello
I don’t know for other variable types, but is it safe to use %s like this?
It is certainly quicker than specifying always the type each time.
using
%sautomatically callsstron the variable. Since everything has__str__defined, you should be able to do this without a problem (i.e. no exception will be raised). However, what you actually will have printed is another story …Note that in newer python code, there’s another option which uses the
formatmethod:This works basically the same way except that it is more powerful once you learn the syntax.