# When to use %r instead of %s in Python?

PythonServer Side ProgrammingProgramming

The %s specifier converts the object using str(), and %r converts it using repr().

For some objects such as integers, they yield the same result, but repr() is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents. For example, if you have a string with endline characters, %s would actually show stuff on new lines while %r would just give the output as \n and also keep the quotes intact.

### For example

>>> string = "Hello\nworld"
>>> print "Example: %s" % string
Example: Hello
world
>>> print "Example: %r" % string
Example: 'Hello\nworld'

You can use the second expression to actually recreate the object.

Published on 18-Dec-2017 08:12:46