Tuesday, July 21, 2015

Python 2.7 tricks

1) map() with an initial argument of None is similar to zip():

>>> a = (1,)
>>> b = (2, 3, 4)
>>> c = (5, 6)

>>> map(None, a, b, c)
[
 (1, 2, 5), 
 (None, 3, 6), 
 (None, 4, None)
]

>>> zip(a, b, c)
[(1, 2, 5)]

2) startswith() and endswith() accept tuples as suffix:

>>> ext.endswith(('.exe', '.dll'))
>>> filename.startswith(('img', 'pic', 'logo'))

3) str.center(width[, fillchar])

>>> 'text'.center(10)
'   text   '
>>> 'text'.center(10, '-')

'---text---'

4) filter(function, iterable) with None as a function is the same as bool as a function.

>>> filter(None, [1, 0, 2, 3, 4, None, 5])
[1, 2, 3, 4, 5]

>>> filter(bool, [1, 0, 2, 3, 4, None, 5])
[1, 2, 3, 4, 5]

5) str.split([sep[, maxsplit]) with sep as None or not specified all consecutive whitespaces are regarded as a single separator:

>>> 'This  is  a string'.split(None)
['This', 'is', 'a', 'string']
>>> 'This  is  a string'.split()
['This', 'is', 'a', 'string']
But if sep is ' ':
>>> 'This  is  a string'.split(' ')
['This', '', 'is', '', 'a', 'string']

6) Operator <> is the same as !=

7) It is possible to use several context managers on one line:

with open('in_file_a', 'r') as in_file_a, open('out_file_a', 'w') as out_file_a, open('out_file_c', 'a') as out_file_c:
    pass

6 comments:

  1. 토토365프로
    스포츠토토


    Useful info. Lucky me I found your web site
    by chance, and I am surprised why this twist of fate
    didn't came about in advance! I bookmarked it.

    ReplyDelete
  2. 스포츠토토티비
    스포츠중계


    Hi there everyone, it's my first visit at this web site,
    and post is actually fruitful in favor of me, keep up posting these types of articles.

    ReplyDelete
  3. Great post, very informative. I wonder why the other experts of this sector do not realize this. You should continue your writing. I am sure, you have a huge readers’ base already! 메이저사이트

    ReplyDelete
  4. These are in fact wonderful ideas in concerning blogging.
    You have touched some good factors here. Any way keep up writing. 경마사이트

    ReplyDelete
  5. My brother suggested I might like this website.
    He was totally right. This post actually made my day.
    You can not imagine simply how much time I had spent for this info!
    Thanks! 바카라

    ReplyDelete
  6. Hello! I just would like to offer you a huge thumbs up for
    the excellent info you have right here on this post. I am coming back to
    your website for more soon. 사설토토

    ReplyDelete