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
• 58,100 points
1,125 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,520 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,300 points
1,242 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, 2019 in Python by Nymeria
• 3,560 points
1,729 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, 2019 in Python by aryya
• 7,460 points
1,558 views
0 votes
1 answer
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,391 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
3,995 views
+1 vote
5 answers

how to exit a python script in an if statement

Instead of using the normal UTF-8 encoding, ...READ MORE

answered Jul 4, 2023 in Python by bodymist
• 140 points
355,000 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,520 points
28,092 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP