Hidden features of Python

What are the lesser-known but useful features of the Python programming language?

  • Try to limit answers to Python core.
  • One feature per answer.
  • Give an example and short description of the feature, not just a link to documentation.
  • Label the feature using a title as the first line.
  • Quick links to answers:

  • Argument Unpacking
  • Braces
  • Chaining Comparison Operators
  • Decorators
  • Default Argument Gotchas / Dangers of Mutable Default arguments
  • Descriptors
  • Dictionary default .get value
  • Docstring Tests
  • Ellipsis Slicing Syntax
  • Enumeration
  • For/else
  • Function as iter() argument
  • Generator expressions
  • import this
  • In Place Value Swapping
  • List stepping
  • __missing__ items
  • Multi-line Regex
  • Named string formatting
  • Nested list/generator comprehensions
  • New types at runtime
  • .pth files
  • ROT13 Encoding
  • Regex Debugging
  • Sending to Generators
  • Tab Completion in Interactive Interpreter
  • Ternary Expression
  • try/except/else
  • Unpacking+ 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的隐藏功能