Main Content

Backquote, backtic, str and repr in Python - conversion object to string

Archive - Originally posted on "The Horse's Mouth" - 2012-07-05 07:46:12 - Graham Ellis

The backquote or backtic operator in Python is a pseudonym for the repr function.

If you have an object that you want to convert into a string (to manipulate it, store it, print it out), Python may call one of two standard method:

__str__ (also the str function) converts an object into a human-readable form - the sort of thing that your program's user might wish to see if you print an object out.

__repr__ (also the repr function) converts an object into a string which is what you as the programmer would wish to be fed back for debugging purposes.

The base object class from which every objects is derived these days includes a __repr__ method which returns a string containing the object type and id / memory address. There is no __str__ method in the base object, and the system will fallback to running __repr__ if you try to print out / convert to a string an object for which __str__ has not been overwritten.

The Backquote (back quote, backtic, back tic) operator runs repr (hard to find in an online search, as the backquote if often special syntax to or ignored by search engines!)

Sample program and output - [here].