What's the Difference Between %S and %D in Python String Formatting

Python- %s %f %d % etc

This is the Exercise:

As it says, %s (of string) is to replace a string, %f (of float) is to replace a float, and %d (of integer) is to replace an integer

# change this code
mystring = "hello"
myfloat = 10.0
myint = 20

# testing code
if mystring == "hello":
print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
print("Integer: %d" % myint)

What's the difference between %r, %s and %d in python?

This is explained in the Python documentation. In short,

  • %d will format a number for display.
  • %s will insert the presentation string representation of the object (i.e. str(o))
  • %r will insert the canonical string representation of the object (i.e. repr(o))

If you are formatting an integer, then these are equivalent. For most objects this is not the case.

What is the difference between %i and %d in Python?

Python copied the C formatting instructions.

For output, %i and %d are the exact same thing, both in Python and in C.

The difference lies in what these do when you use them to parse input, in C by using the scanf() function. See Difference between format specifiers %i and %d in printf.

Python doesn't have a scanf equivalent, but the Python string formatting operations retained the two options to remain compatible with C.

The new str.format() and format() format specification mini-language dropped support for i and stuck with d only.

python string formatting {:d} vs %d on floating point number

The two implementations are quite separate, and some warts in the % implementation were ironed out. Using %d for floats may mask problems in your code, where you thought you had integers but got floating point values instead. Imagine a value of 1.999999 and only seeing 1 instead of 2 as %d truncates the value.

As such, the float.__format__() hook method called by str.format() to do the actual conversion work does not support the d format and throws an exception instead.

You can use the {:.0f} format to explicitly display (rounded) floating point values with no decimal numbers:

>>> '{:.0f}'.format(1.234)
'1'
>>> '{:.0f}'.format(1.534)
'2'

or use int() before formatting to explicitly truncate your floating point number.

As a side note, if all you are doing is formatting a number as a string (and not interpolating into a larger string), use the format() function:

>>> format(1.234, '.0f')
'1'

This communicates your intent better and is a little faster to boot.

String formatting: % vs. .format vs. f-string literal

To answer your first question... .format just seems more sophisticated in many ways. An annoying thing about % is also how it can either take a variable or a tuple. You'd think the following would always work:

"Hello %s" % name

yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you'd need to do

"Hello %s" % (name,)   # supply the single argument as a single-item tuple

which is just ugly. .format doesn't have those issues. Also in the second example you gave, the .format example is much cleaner looking.

Only use it for backwards compatibility with Python 2.5.


To answer your second question, string formatting happens at the same time as any other operation - when the string formatting expression is evaluated. And Python, not being a lazy language, evaluates expressions before calling functions, so the expression log.debug("some debug info: %s" % some_info) will first evaluate the string to, e.g. "some debug info: roflcopters are active", then that string will be passed to log.debug().

Python the Hard Way - exercise 6 - %r versus %s

They are called string formatting operations.

The difference between %s and %r is that %s uses the str function and %r uses the repr function. You can read about the differences between str and repr in this answer, but for built-in types, the biggest difference in practice is that repr for strings includes quotes and all special characters are escaped.

What does %s mean in a Python format string?

It is a string formatting syntax (which it borrows from C).

Please see "PyFormat":

Python supports formatting values into
strings. Although this can include
very complicated expressions, the most
basic usage is to insert values into a
string with the %s placeholder.

Here is a really simple example:

#Python 2
name = raw_input("who are you? ")
print "hello %s" % (name,)

#Python 3+
name = input("who are you? ")
print("hello %s" % (name,))

The %s token allows me to insert (and potentially format) a string. Notice that the %s token is replaced by whatever I pass to the string after the % symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.



Related Topics



Leave a reply



Submit