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

3 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. 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
  3. These are in fact wonderful ideas in concerning blogging.
    You have touched some good factors here. Any way keep up writing. 경마사이트

    ReplyDelete