Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 814
Ricky Robinson Avatar asked Jan 24 '13 16:01

Ricky Robinson


People also ask

Can we use %s in Python?

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.

Can we use %s for Integer in Python?

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

What is the difference between %D and %S in Python?

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.

What does %s %d in Python?

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.


1 Answers

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.

like image 137
mgilson Avatar answered Sep 30 '22 18:09

mgilson