Computer Science, asked by rishu7803, 10 months ago

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

Answers

Answered by herin83
0

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.

Similar questions