Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between !r and %r in Python?

As the title states, what is the difference between these two flags? It seems they both convert the value to a string using repr()? Also, in this line of code:

"{0!r:20}".format("Hello")   

What does the 0 in front of the !r do?

like image 647
b_pcakes Avatar asked Oct 13 '15 07:10

b_pcakes


People also ask

What is %r in Python?

PythonServer Side ProgrammingProgramming. The %s specifier converts the object using str(), and %r converts it using repr().

Which is best R or Python?

Speed and performance. Python is beginner-friendly, which can make it a faster language to learn than R. Depending on the problem you are looking to solve, R is better suited for data experimentation and exploration. Python is a better choice for large-scale applications and machine learning.

Is Python or R better for data cleaning?

Learning R and Python Most data scientists will agree that Python is the easier of the two to learn, especially if one already has a background in programming and is familiar with OOP languages. Its syntax was modeled after natural language, making it faster to learn and code.

Which is faster R or Python?

R is not the fastest, but you get a consistent behavior compared to Python: the slowest implementation in R is ~24x slower than the fastest, while in Python is ~343x (in Julia is ~3x);


1 Answers

%r is not a valid placeholder in the str.format() formatting operations; it only works in old-style % string formatting. It indeed converts the object to a representation through the repr() function.

In str.format(), !r is the equivalent, but this also means that you can now use all the format codes for a string. Normally str.format() will call the object.__format__() method on the object itself, but by using !r, repr(object).__format__() is used instead.

There are also the !s and (in Python 3) !a converters; these apply the str() and ascii() functions first.

The 0 in front indicates what argument to the str.format() method will be used to fill that slot; positional argument 0 is "Hello" in your case. You could use named arguments too, and pass in objects as keyword arguments:

"{greeting!r:20}".format(greeting="Hello")   

Unless you are using Python 2.6, you can omit this as slots without indices or names are automatically numbered; the first {} is 0, the second {} takes the second argument at index 1, etc.

like image 53
Martijn Pieters Avatar answered Sep 28 '22 11:09

Martijn Pieters