When to use %r instead of %s in Python? [duplicate]

0 votes

x = "There are %d types of people." % 10 ... print "I said: %r." % x

Why is %r used here instead of %s? When would you use %r, and when would you use %s?

Aug 2, 2018 in Python by Priyaj
• 56,920 points
71 views

1 answer to this question.

0 votes

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.

Here's an example, using a date:

>>> import datetime

>>> d = datetime.date.today()

>>> str(d) '2011-05-14'

>>> repr(d) 'datetime.date(2011, 5, 14)'

Types for which repr() doesn't produce Python syntax include those that point to external resources such as a file, which you can't guarantee to recreate in a different context.

answered Aug 2, 2018 by bug_seeker
• 15,350 points

Related Questions In Python

0 votes
1 answer

When to use file vs open in Python?

File() has been removed since Python 3.0 ...READ MORE

answered Oct 30, 2018 in Python by SDeb
• 13,180 points
33 views
0 votes
1 answer

How to zip with a list output in Python instead of a tuple output?

Good question - Considering that you are ...READ MORE

answered Feb 7 in Python by Nymeria
• 3,520 points
49 views
0 votes
1 answer

When is the perfect time to use Tornado in python?

There is a server and a webframework. ...READ MORE

answered Feb 14 in Python by ariaholic
• 7,340 points
61 views
0 votes
1 answer
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 344 views
+4 votes
6 answers
0 votes
1 answer

how to exit a python script in an if statement

This works fine for me: while True: ...READ MORE

answered Sep 19, 2018 in Python by bug_seeker
• 15,350 points
4,512 views
0 votes
1 answer

Create an empty list in python with certain size

Try this instead: lst = [None] * 10 The ...READ MORE

answered Aug 2, 2018 in Python by bug_seeker
• 15,350 points
825 views