Python中的一些魔法

  1. 将多个序列串放在一起遍历:

    1
    2
    3
    4
    5
    6
    >>> from itertools import chain  
    >>> a = [1, 2, 3, 4]
    >>> b = ['a', 'b', 'c']
    >>> for x in chain(a, b):
    ... print(x)
    ...
  2. python表示昨天的日期:

    1
    2
    3
    4
    5
    6
    7
    8
    #-*-coding:utf-8-*-  
    import datetime

    def getYesterday(): #
    today=datetime.date.today()
    oneday=datetime.timedelta(days=1)
    yesterday=today-oneday
    return yesterday
  3. 打印代码出错信息:

    1
    2
    import traceback
    traceback.format_exc()

traceback.print_exc()跟traceback.format_exc()有什么区别呢?
format_exc()返回字符串,print_exc()则直接给打印出来。