What are options for keeping as close to the python2 way of printing.
>>> x1='hi'
>>> x2='there'
>>> print "Val1=%s Val2=%s" %(x1,x2)
File "<stdin>", line 1
print "%s" %x
^
SyntaxError: invalid syntax
It would not be necessary to mention : "lose your 'old' way of thinking and use the {} in python3." I am aware of the "blessed" python3 syntax, and given it is not in my estimation preferable, would like to see what other options exist.
thanks.
That is still valid syntax in python 3, but print is no longer a statement. It is a function, so you must put parentheses:
print("%s" % x)
None. Avoid print/print() entirely if you want perfect compatibility.
sys.stdout.write('%s\n' % (x,))
Related
I was messing around with both Python 3.8 and 2.7 and found out that the print function in Python 3 doesn't allow leading zeros in print. See below:
>>> print(01)
File "<stdin>", line 1
print(01)
^
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
I suppose this happens because Python 3.x differentiate data types even when printing, this is why the following works:
>>> print('01')
01
I explicitly asked to print a string. Though in Python 2.7 there is no error with the following statement:
>>> print '01'
01
It just returns what I asked. Does it mean that Python 2.x always converts print values into strings?
In original python 2, print is a statement, and does not return a value at all.
>>> x=print 'hi'
File "<stdin>", line 1
x=print 'hi'
^
SyntaxError: invalid syntax
If you use the future-compatible print function in python 2.7, say, it behaves exactly like Python 3.
In Python 3, print, a function, always returns None. It prints to a file (often the standard output), but the value returned from the function is None.
>>> x=print(1)
1
>>> x
>>> type(x)
<type 'NoneType'>
As for 1 vs 01, in Python 2, a number with a leading zero is octal:
>>> 010
8
This syntax is illegal in Python 3, so you get SyntaxError: invalid token. This happens before the print statement ever sees what's going on, so it has nothing to do with print.
If you want to write a number in octal in Python3, the correct syntax is 0o... as in:
>>> 0o10
8
When I run the following program in python 2.7.5 I get
>>> x=23
>>> print x
23
Ok fine.
Similarly, type(x) is int.
When I run the following program:
>>> print 23./4
5.75
Still fine. But then when I run this final program:
>>> x=23
>>> print x./23
>>> File "<stdin>", line 1
print x./4
^SyntaxError: invalid syntax
i.e. I get a syntax error. But I can do other arithmetical operations with x treating it as though it were the integer 23; x+1 yields 24, x/23 yields 1 and so on. So what is going on here? p.s. this is my first post hopefully the formatting is ok.
Notice that the following program also fails:
x = 10
print x5
even though this program works:
print 105
If the above makes sense, then the only missing part here is understanding that 23. is a short for 23.0, it's a single entity, not two separate (23 and .).
If however my above example also seems not intuitive to you, then your understanding of variables is a little off, and I would recommend revisiting the chapter on variables in whichever textbook you are using.
The decimal point can be part of a numeric literal. You can't use it (as a decimal point) after a variable; in that context it would be interpreted as attribute access and would need an attribute name after it. For the same reason, you can do 23/4, but you can't set x=2 and then do x3/4. Using a variable does not mean its literal value is textually pasted into the code at that point.
Instead of doing that, to achieve that result, you have to change one of the type of one of the part of the division into float and you don't need the . sign. Here is what your code should be:
x = 23
print x / float(4)
Or you can make it like this
x = 23
print float(x) / 4
It will give you your desired result which is 5.75
Hope it helps
I have this line of code:
print ("(x %s)(x %s)") % (var_p1, var_p2)
But it does not work, I am new to programming and I don't know what I have done wrong. Any experts out there with a simple answer?
I wanted it to randomly select an equation for a parabola. e.g. (x-3)(x+1) However, it comes up with the error message:
Traceback (most recent call last):
"File "E:/Python34/MyFiles/Math Study Buddy.py", line 26 in <module>
print ("(x %s)(x %s)") % (var_p1, var_p2)
TypeError: unsupported operand type (s) for %: 'NoneType' and 'tuple'
As you are in python 3 you need to put the variables inside the parenthesis after your string:
>>> print ("(x %s)(x %s)"%(2, 3))
(x 2)(x 3)
Note that in python 3 print is a function and you need to pass the string as its argument.So you can not put your variables outside the function!
For more detail read printf-style String Formatting
Note
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str.format() interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.
You can use str.format
>>> var_p1 = 'test'
>>> var_p2 = 'test2'
>>> print(("(x {})(x {})".format(var_p1, var_p2)))
(x test)(x test2)
you don't need to use 'x' to substitude variables here.
This will fix:
print ("(%s)(%s)") % (var_p1, var_p2)
also, .format is better than %
see:
Python string formatting: % vs. .format
Python 2.7.3
>>> print '%2.2f' % 0.1
0.10
The documentation I have says that type % should be the same as type f except that the input is multiplied by 100.
>>> print '%2.2%' % 0.1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
use the new format expression, which has the formatter you are referring to
print "{:%}".format(0.1)
#10.000000%
if you just want the integer part you can use the precision specification
print "{:.0%}".format(0.1)
#10%
see the doc at
http://docs.python.org/2/library/string#formatspec
To expand a little bit, the new format specificator is really more powerful than the old one. First of all it's really simple calling the parameters by order or name
"play the {instrument} all {moment}, even if my {instrument} is old".format(moment='day', instrument='guitar')
#'play the guitar all day, even if my guitar is old'
then, as can be seen in the documentation, is possible to have access to properties of the object:
"the real component is {0.real} and the imaginary one is {0.imag}".format(3+4j)
#'the real component is 3.0 and the imaginary one is 4.0'
There is a lot more than this, but you can find it all in the documentation, that is very clear.
Came across this question. In Python 3 you can simply use fstrings (thus avoiding the .format) in a similar way as described above. The format is:
print(f"{your_number:.n_decimals%}")
Eg.
>>> print(f"{0.0350:.2%}")
3.50%
print '%2.2%' % 0.1
Tells it that there are 2 placeholders in format string (%), so you have a complain
I was going through http://web2py.com/book/default/chapter/02 and found this:
>>> print 'number is ' + str(3)
number is 3
>>> print 'number is %s' % (3)
number is 3
>>> print 'number is %(number)s' % dict(number=3)
number is 3
It has been given that The last notation is more explicit and less error prone, and is to be preferred.
I am wondering what is the advantage of using the last notation.. will it not have a performance overhead?
>>> print 'number is ' + str(3)
number is 3
This is definitely the worst solution and might cause you problems if you do the beginner mistake "Value of obj: " + obj where obj is not a string or unicode object. For many concatenations, it's not readable at all - it's similar to something like echo "<p>Hello ".$username."!</p>"; in PHP (this can get arbitrarily ugly).
print 'number is %s' % (3)
number is 3
Now that is much better. Instead of a hard-to-read concatenation, you see the output format immediately. Coming back to the beginner mistake of outputting values, you can do print "Value of obj: %r" % obj, for example. I personally prefer this in most cases. But note that you cannot use it in gettext-translated strings if you have multiple format specifiers because the order might change in other languages.
As you forgot to mention it here, you can also use the new string formatting method which is similar:
>>> "number is {0}".format(3)
'number is 3'
Next, dict lookup:
>>> print 'number is %(number)s' % dict(number=3)
number is 3
As said before, gettext-translated strings might change the order of positional format specifiers, so this option is the best when working with translations. The performance drop should be negligible - if your program is not all about formatting strings.
As with the positional formatting, you can also do it in the new style:
>>> "number is {number}".format(number=3)
'number is 3'
It's hard to tell which one to take. I recommend you to use positional arguments with the % notation for simple strings and dict lookup formatting for translated strings.
I can think of a few differences.
First to me is cumbersome, if more than one variable is involved. I can not speak of performance penalty on that. See additional arguments below.
The second example is positional dependent and it can be easy to change position causing errors. It also does not tell you anything about the variables.
The third example, the position of variables is not important. You use a dictionary. This makes it elegant as it does not rely on positional structuring of variables.
See the example below:
>>> print 'number is %s %s' % (3,4)
number is 3 4
>>> print 'number is %s %s' % (4,3)
number is 4 3
>>> print 'number is %(number)s %(two)s' % dict(number=3, two=4)
number is 3 4
>>> print 'number is %(number)s %(two)s' % dict(two=4, number=3)
number is 3 4
>>>
Also another part of discussion on this
"+" is the string concatenation operator.
"%" is string formatting.
In this trivial case, string formatting accomplishes the same result as concatenation. Unlike string formatting, string concatenation only works when everything is already a string. So if you miss to convert your variables to string, concatenation will cause error.
[Edit: My answer was biased towards templating since the question came from web2py where templates are so commonly involved]
As Ryan says below, the concatenation is faster than formatting.
Suggestion is
Use the first form - concatenation, if you are concatenating just two strings
Use the second form, if there are few variables. You can invariably see the positions and deal with them
Use the third form when you are doing templating i.e. formatting a large piece of string with variable data. The dictionary form helps in providing meaning to variables inside the large piece of text.
I am wondering what is the advantage
of using the last notation..
Hm, as you said, the last notation is really more explicit and actually is less error prone.
will it not have a performance
overhead?
It will have little performance overhead, but it's minor if compared with data fetching from DB or network connections.
It's a bad, unjustified piece of advice.
The third method is cumbersome, violates DRY, and error prone, except if:
You are writing a framework which don't have control over the format string. For example, logging module, web2py, or gettext.
The format string is extremely long.
The format string is read from a file from a config file.
The problem with the third method should be obvious when you consider that foo appears three times in this code: "%(foo)s" % dict(foo=foo). This is error prone. Most programs should not use the third method, unless they know they need to.
The second method is the simplest method, and is what you generally use in most programs. It is best used when the format string is immediate, e.g. 'values: %s %s %s' % (a, b, c) instead of taken from a variable, e.g. fmt % (a, b, c).
The first concatenation is almost never useful, except perhaps if you're building list by loops:
s = ''
for x in l:
s += str(x)
however, in that case, it's generally better and faster to use str.join():
s = ''.join(str(x) for x in l)