Python string formatting: can I use% s for all types?

When doing string formatting in Python, I noticed that it %salso converts 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 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.

+5
source share
4 answers

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 ...

, python , format:

'Integer: {}; Float: {}; String: {}'.format(a,b,c)

, , , .

+13

, , %s; .

, %d %f, . . .

, Python 2.6 , .format():

print 'Integer: {0}; Float: {1}; String: {2}'.format(a, b, c)

, , .

+5

- , .

>>> 'integer: {} float: {} string: {}'.format(1, 1.1, 'blah')
'integer: 1 float: 1.1 string: blah'

, str(obj) :

>>> format(1)
'1'
>>> format(1.1)
'1.1'
>>> format('blah')
'blah'

:

>>> format(12345, '>10,')
'    12,345'
+1

, , % 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.

+1
source

All Articles