Not enough arguments?

print "%r" 

vs

 print "%r %r"%("hello") 

I want to compare the above two lines of code in python. The last statement gives an error with insufficient arguments for printing, but in the first case we have no arguments, but it still works. Can someone explain this to someone who is new to programming. Any help would be greatly appreciated.

+4
source share
5 answers

% inside a line comes into play only after Python has determined that you use the % printf-like operator outside the line.

In the first case, you are not, so he does not complain. All you do in this case is print a line.

In the second case, you use the % operator, so it complains that you did not provide enough arguments. In this case, you format the string before printing it.

print itself knows nothing about string formatting functions; it just prints what you give it. When formatting strings, something like "Hello, %s"%("Pax") processed by the % operator to provide you with "Hello, Pax" , and then to output:

 print "Hello, %s"%("Pax") # ^ \_________________/ <- This bit done first # | # Then the print is done 

Basically, the % operator, which decides that you are doing printf-style processing, and not the fact that you have a string containing the % character. This is confirmed by the fact that:

 print "%r %r %r %r %r" 

also has no problem with argument counter mismatch by printing the literal %r %r %r %r %r .

+12
source

print "%r" just prints the string %r .

print "%r %r" % ("hello") . % after the line %r %r is called the formatting operator and, because of this, %r here has a special meaning - it is a placeholder for what you want to place on it.

You have two lines of %r in a line: you should have two lines:

 print "%r %r" % ("hello", "world") 

Also see documents in line formatting .

+3
source

You are not reading the error message:

 >>> print "%r %r"%("hello") Traceback (most recent call last): File "<pyshell>", line 1, in <module> print "%r %r"%("hello") TypeError: not enough arguments for format string 

This is a format string in which there are not enough arguments, not a fingerprint. This shows the same problem:

 >>> "%r %r"%("hello") Traceback (most recent call last): File "<pyshell>", line 1, in <module> "%r %r"%("hello") TypeError: not enough arguments for format string 

While this works:

 >>> "%r %r"%("hello", "world") "hello world" 
+3
source

It is worth noting that the only argument you give print in all cases is a string. The Python interpreter evaluates any string formatting before calling print .

As @paxdiablo reports, when you give no argument to the %r format specifier, Python assumes that you want the string to be as it is and does not complain.

+3
source

The second line requires two arguments - there are two "% r", so you need two arguments in brackets, for example:

 print "%r %r" % ("hello", "world") 

Refer to the documentation .

0
source

Source: https://habr.com/ru/post/1497394/


All Articles