What is the meaning of %r? - python

What's the meaning of %r in the following statement?
print '%r' % (1)
I think I've heard of %s, %d, and %f but never heard of this.

Background:
In Python, there are two builtin functions for turning an object into a string: str vs. repr. str is supposed to be a friendly, human readable string. repr is supposed to include detailed information about an object's contents (sometimes, they'll return the same thing, such as for integers). By convention, if there's a Python expression that will eval to another object that's ==, repr will return such an expression e.g.
>>> print repr('hi')
'hi' # notice the quotes here as opposed to...
>>> print str('hi')
hi
If returning an expression doesn't make sense for an object, repr should return a string that's surrounded by < and > symbols e.g. <blah>.
To answer your original question:
%s <-> str
%r <-> repr
In addition:
You can control the way an instance of your own classes convert to strings by implementing __str__ and __repr__ methods.
class Foo:
def __init__(self, foo):
self.foo = foo
def __eq__(self, other):
"""Implements ==."""
return self.foo == other.foo
def __repr__(self):
# if you eval the return value of this function,
# you'll get another Foo instance that's == to self
return "Foo(%r)" % self.foo

It calls repr() on the object and inserts the resulting string.

Adding to the replies given above, '%r' can be useful in a scenario where you have a list with heterogeneous data type.
Let's say, we have a list = [1, 'apple' , 2 , 'r','banana']
Obviously in this case using '%d' or '%s' would cause an error. Instead, we can use '%r' to print all these values.

It prints the replacement as a string with repr().

The difference between %r and %s is, %r calls the repr() method and %s calls the str() method. Both of these are built-in Python functions.
The repr() method returns a printable representation of the given object.
The str() method returns the "informal" or nicely printable representation of a given object.
In simple language, what the str() method does is print the result in a way which the end user would like to see:
name = "Adam"
str(name)
Out[1]: 'Adam'
The repr() method would print or show what an object actually looks like:
name = "Adam"
repr(name)
Out[1]: "'Adam'"

%s <=> str
%r <=> repr
%r calls repr() on the object, and inserts the resulting string returned by __repr__.
The string returned by __repr__ should be unambiguous and, if possible, match the source code necessary to recreate the object being represented.
A quick example:
class Foo:
def __init__(self, foo):
self.foo = foo
def __repr__(self):
return 'Foo(%r)' % self.foo
def __str__(self):
return self.foo
test = Foo('Text')
So,
in[1]: test
Out[1]: Foo('Text')
in[2]: str(test)
Out[2]: 'Text'

%s calls the __str()__ method of the selected object and replaces itself with the return value,
%r calls the __repr()__ method of the selected object and replaces itself with the return value.

See String Formatting Operations in the docs. Notice that %s and %d etc, might work differently to how you expect if you are used to the way they work in another language such as C.
In particular, %s also works well for ints and floats unless you have special formatting requirements where %d or %f will give you more control.

I read in "Learning Python the Hard Way", the author said that
%r is the best for debugging, other formats are for displaying variables to users

Related

Return object name instead of its memory address [duplicate]

I want to set the name of a class to one of the variables within the class so that when I print classes I get their names, I've tried setting __name__ but it did not work.
this is my class
class SNMPData(object):
def __init__(self, device='', speed_down=0, speed_up=0, bgp_peer_state='', bgp_summary='', error=''):
self.device = device
self.speed_down = speed_down
self.speed_up = speed_up
self.bgp_peer_state = bgp_peer_state
self.bgp_summary = bgp_summary
self.error = error
self.__name__ = device
I create a list of objects then try print them
>>> list = [SNMPData(device='dev_1',speed_down=1),SNMPData(device='dev_2',speed_down=2)]
>>> print(list)
[<SNMPData object at 0x7ff052a42ef0>, <SNMPData object at 0x7ff052a42b38>]
>>>
instead of SNMPData object at 0x.... is it possible to print
['SNMPData dev_1','SNMPData dev_2']
instead?
You are looking to define __repr__ which should return a printable representation of the object. The official definition of __repr__
repr(object):
Return a string containing a printable representation of an object.
For many types, this function makes an attempt to return a string that
would yield an object with the same value when passed to eval(),
otherwise the representation is a string enclosed in angle brackets
that contains the name of the type of the object together with
additional information often including the name and address of the
object. A class can control what this function returns for its
instances by defining a repr() method.
bottom line is that the output from __str__ is meant to be readable by human ** whereas the output from **__repr__ is meant to be read by the Python interpreter. so when you give the string to the interpreter, it should recreate the object. Also If an object doesn't have a __str__ method then __repr__ is used instead.
Each class has a __repr__ and __str__ function which takes a single argument, self, representing the object itself. The __repr__ function returns the true string representation of the object and the __str__ function is used for str(obj) which is used for printing.
class SNMPData(object):
def __init__(self, device='', speed_down=0, speed_up=0, bgp_peer_state='', bgp_summary='', error=''):
...
def __repr__(self):
return '{} {}'.format(self.__class__.__name__, self.device)
You can do the same for __str__(self) if you want to observe this behaviour for printing.
You are able to change a text representation of your custom object by overriding __repr__ and __str__ methods:
...
def __repr__(self):
return self.__class__.__name__ + ' ' + self.device
Define __repr__(self) and __str__(self).
The former is the "official" string representation. The latter is what is returned when you cast the object to a str.
Generalizing some of the other answers, you could do:
def __str__(self):
return '{self.__class__.__name__} {self.device}'.format(self=self)

Set name of object in class

I want to set the name of a class to one of the variables within the class so that when I print classes I get their names, I've tried setting __name__ but it did not work.
this is my class
class SNMPData(object):
def __init__(self, device='', speed_down=0, speed_up=0, bgp_peer_state='', bgp_summary='', error=''):
self.device = device
self.speed_down = speed_down
self.speed_up = speed_up
self.bgp_peer_state = bgp_peer_state
self.bgp_summary = bgp_summary
self.error = error
self.__name__ = device
I create a list of objects then try print them
>>> list = [SNMPData(device='dev_1',speed_down=1),SNMPData(device='dev_2',speed_down=2)]
>>> print(list)
[<SNMPData object at 0x7ff052a42ef0>, <SNMPData object at 0x7ff052a42b38>]
>>>
instead of SNMPData object at 0x.... is it possible to print
['SNMPData dev_1','SNMPData dev_2']
instead?
You are looking to define __repr__ which should return a printable representation of the object. The official definition of __repr__
repr(object):
Return a string containing a printable representation of an object.
For many types, this function makes an attempt to return a string that
would yield an object with the same value when passed to eval(),
otherwise the representation is a string enclosed in angle brackets
that contains the name of the type of the object together with
additional information often including the name and address of the
object. A class can control what this function returns for its
instances by defining a repr() method.
bottom line is that the output from __str__ is meant to be readable by human ** whereas the output from **__repr__ is meant to be read by the Python interpreter. so when you give the string to the interpreter, it should recreate the object. Also If an object doesn't have a __str__ method then __repr__ is used instead.
Each class has a __repr__ and __str__ function which takes a single argument, self, representing the object itself. The __repr__ function returns the true string representation of the object and the __str__ function is used for str(obj) which is used for printing.
class SNMPData(object):
def __init__(self, device='', speed_down=0, speed_up=0, bgp_peer_state='', bgp_summary='', error=''):
...
def __repr__(self):
return '{} {}'.format(self.__class__.__name__, self.device)
You can do the same for __str__(self) if you want to observe this behaviour for printing.
You are able to change a text representation of your custom object by overriding __repr__ and __str__ methods:
...
def __repr__(self):
return self.__class__.__name__ + ' ' + self.device
Define __repr__(self) and __str__(self).
The former is the "official" string representation. The latter is what is returned when you cast the object to a str.
Generalizing some of the other answers, you could do:
def __str__(self):
return '{self.__class__.__name__} {self.device}'.format(self=self)

I don't get what's the difference between format() and ... (python)

Confused newbie here. What's the difference between using:
print ("So you are {0} years old".format(age))
AND
print ("So you are", age, "years old")
Both work.
Actually there's a huge difference. The former use string's format method to create a string. The latter, pass several arguments to print function, which will concatenate them all adding a whitespace (default) between them.
The former is far more powerful, for instance, you can use the format syntax to accomplish things like:
# trunc a float to two decimal places
>>> '{:.2f}'.format(3.4567)
'3.46'
# access an objects method
>>> import math
>>> '{.pi}'.format(math)
'3.141592653589793'
It is similar to printf style formats used in earlier versions of python with the % operator: (ie: "%d" % 3) Now str.format() is recommended over the % operator and is the new standard in Python 3.
>>> class Age:
... def __format__(self, format_spec):
... return "{:{}}".format("format", format_spec)
... def __str__(self):
... return "str"
...
>>> age = Age()
>>> print(age)
str
>>> print("{:s}".format(age))
format
format() allows to convert the same object into a string using different representations specified by format_spec. print uses __str__ or __repr__ if the former is not defined. format() may also use __str__, __repr__ if __format__ is not defined.
In Python 2 you could also define __unicode__ method:
>>> class U:
... def __unicode__(self):
... return u"unicode"
... def __str__(self):
... return "str"
... def __repr__(self):
... return "repr"
...
>>> u = U()
>>> print(u"%s" % u)
unicode
>>> print(u)
str
>>> print(repr(u))
repr
>>> u
repr
There is also ascii() builtin function in Python 3 that behaves like repr() but produces ascii-only results:
>>> print(ascii("🐍"))
'\U0001f40d'
See U+1F40D SNAKE.
format() uses Format Specification Mini-Language instead of running various conversion to string functions.
An object may invent its own format_spec language e.g., datetime allows to use strftime formats:
>>> from datetime import datetime
>>> "{:%c}".format(datetime.utcnow())
'Sun May 4 18:51:18 2014'
The former is more convenient. Imagine if you have lots of parameters, you'll end up with something like this:
print ("So your name is ", firstname, " ", lastname, " and you are ", age, " years old")
This is a pain to both read and write. So the format method is there to help you write cleaner and more readable strings.

python, how to call function in as parameter in self.response.out.write()

class GuestBook(webapp.RequestHandler):
def post(self):
self.response.out.write(
'<h2>You wrote:</h2> %s' %self.request.get('content') )
I want to pass this: %self.request.get('content') into a function. And use function return in the old place.I am python newbie. I tried.but failed. need help!
This is my function; I defined it in the same class as below.
def ept(str)
str = str + " is good."
return str
And I call it in the old place like:
ept(%self.request.get('content'))
Could anybody help me, what is wrong with my code
First of all you ought to (re-)read about string interpolation
The % is an operator applicable to string and unicode objects, so such an object must precede its usage. So you could do
def ept(s):
return "%s is good" % s
ept(self.request.get('content'))
% is applicable to integers as well, but that's a different story.

How to apply __str__ function when printing a list of objects in Python [duplicate]

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Closed 7 months ago.
Well this interactive python console snippet will tell everything:
>>> class Test:
... def __str__(self):
... return 'asd'
...
>>> t = Test()
>>> print(t)
asd
>>> l = [Test(), Test(), Test()]
>>> print(l)
[__main__.Test instance at 0x00CBC1E8, __main__.Test instance at 0x00CBC260,
__main__.Test instance at 0x00CBC238]
Basically I would like to get three asd string printed when I print the list. I have also tried pprint but it gives the same results.
Try:
class Test:
def __repr__(self):
return 'asd'
And read this documentation link:
The suggestion in other answers to implement __repr__ is definitely one possibility. If that's unfeasible for whatever reason (existing type, __repr__ needed for reasons other than aesthetic, etc), then just do
print [str(x) for x in l]
or, as some are sure to suggest, map(str, l) (just a bit more compact).
You need to make a __repr__ method:
>>> class Test:
def __str__(self):
return 'asd'
def __repr__(self):
return 'zxcv'
>>> [Test(), Test()]
[zxcv, zxcv]
>>> print _
[zxcv, zxcv]
Refer to the docs:
object.__repr__(self)
Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.
This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

Categories