Hidden features of Python
What are the lesser-known but useful features of the Python programming language?
Quick links to answers:
.get
value import this
__missing__
items .pth
files try/except/else
print()
function with
statement Negative round
The round()
function rounds a float number to given precision in decimal digits, but precision can be negative:
>>> str(round(1234.5678, -2))
'1200.0'
>>> str(round(1234.5678, 2))
'1234.57'
Note: round()
always returns a float, str()
used in the above example because floating point math is inexact, and under 2.x the second example can print as 1234.5700000000001
. Also see the decimal
module.
Multiplying by a boolean
One thing I'm constantly doing in web development is optionally printing HTML parameters. We've all seen code like this in other languages:
class='<% isSelected ? "selected" : "" %>'
In Python, you can multiply by a boolean and it does exactly what you'd expect:
class='<% "selected" * isSelected %>'
This is because multiplication coerces the boolean to an integer (0 for False, 1 for True), and in python multiplying a string by an int repeats the string N times.
Python's advanced slicing operation has a barely known syntax element, the ellipsis:
>>> class C(object):
... def __getitem__(self, item):
... return item
...
>>> C()[1:2, ..., 3]
(slice(1, 2, None), Ellipsis, 3)
Unfortunately it's barely useful as the ellipsis is only supported if tuples are involved.
链接地址: http://www.djcxy.com/p/7412.html上一篇: Python的隐藏功能
下一篇: Python的隐藏功能