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.
The % symbol is used in Python with a large variety of data types and configurations. %s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string.
%s can format any python object and print it is a string. The result that %d and %s print the same in this case because you are passing int/long object. Suppose if you try to pass other object, %s would print the str() representation and %d would either fail or would print its numeric defined value.
They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.
Best Practices for Using %s and %d in Python Upon inspecting the first line, you'll notice that %d in the format string corresponds to a number in the tuple, while the following %s specifiers correspond to string values in the tuple.
using %s
automatically calls str
on 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 format
method:
'Integer: {}; Float: {}; String: {}'.format(a,b,c)
This works basically the same way except that it is more powerful once you learn the syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With