When doing string formatting in Python, I noticed that it %salso converts numbers to strings.
%s
>>> 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 do not know other types of variables, but is it possible to use %slike this?
This, of course, is faster than specifying a type each time.
using %sautomatically calls strfor a variable. Since everything has it __str__, you should be able to do it without problems (i.e. an exception will not be raised). However, what you actually printed is another story ...
str
__str__
, python , format:
format
'Integer: {}; Float: {}; String: {}'.format(a,b,c)
, , , .
, , %s; .
, %d %f, . . .
%d
%f
, Python 2.6 , .format():
.format()
print 'Integer: {0}; Float: {1}; String: {2}'.format(a, b, c)
, , .
- , .
>>> 'integer: {} float: {} string: {}'.format(1, 1.1, 'blah') 'integer: 1 float: 1.1 string: blah'
, str(obj) :
str(obj)
>>> format(1) '1' >>> format(1.1) '1.1' >>> format('blah') 'blah'
:
>>> format(12345, '>10,') ' 12,345'
, , % s, , .
% s, , , str() .
, % s , , , , , str().
Using other operators, you can specify the format for the value. IE: perhaps you want to have all the floating point numbers in the string represented in 2 decimal places, regardless of the actual number of decimal places required by the number - for this case% s simply will not complete the task.