Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does !r mean in Python? [duplicate]

I have found the following code in a project.

What does the !r part mean?

def __repr__(self):
    return f"user={self.user!r}, variant={self.variant!r}"
like image 346
Nepo Znat Avatar asked Dec 08 '19 10:12

Nepo Znat


People also ask

What does '\ r mean in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.

What is \r in Python example?

A carriage return is nothing but a simple escape character. \n is also an escape character which creates a new line. Carriage return or \r is a very unique feature of Python. \r will just work as you have shifted your cursor to the beginning of the string or line.

What is r in Python regex?

The 'r' at the start of the pattern string designates a python "raw" string which passes through backslashes without change which is very handy for regular expressions (Java needs this feature badly!). I recommend that you always write pattern strings with the 'r' just as a habit.

What is exclamation r in Python?

r (apply repr() ) can be used to convert the value before it is formatted. >>> import math >>> print 'The value of PI is approximately {}. '. format(math.


1 Answers

By default an f-string displays the result of calling str on the values inside the curly braces. Specifying !r displays the result of calling repr instead.

From the docs

The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the format() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling format(), the normal formatting logic is bypassed.

Three conversion flags are currently supported: '!s' which calls str() on the value, '!r' which calls repr() and '!a' which calls ascii().

like image 166
snakecharmerb Avatar answered Oct 16 '22 03:10

snakecharmerb