Python/scripts

From Christoph's Personal Wiki
Revision as of 22:24, 23 December 2015 by Christoph (Talk | contribs) (Miscellaneous)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This article will list a bunch of quick-and-dirty Python tips-and-tricks, examples, code, etc.

Generate a random set of characters

Note: Useful for creating random user passwords after a reset.

$ python -c 'import random; print "".join([random.choice("abcdefghijklmnopqrstuvwxyz0123456789\!@#$%^&*(-_=+)") for i in range(9)])'

Lambda functions

In stead of creating a new function of

f(x): return x + 1

You could use a lambda function inline, like so:

function_var = lambda x: x + 1
>>> print function_var(2)
3

Selective printing

  • Print every 4th character of the English alphabet starting with the letter/character 'c':
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_letters[0:26]
'abcdefghijklmnopqrstuvwxy'
alpha_lc = map(chr, range(97, 123))
alpha_lc = [chr(i) for i in xrange(ord('a'), ord('z')+1)]
alpha_uc = map(chr, range(65, 91))
alpha_ns = 'abcdefghijklmnopqrstuvwxyz'
alpha_sp = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 
            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 
            'u', 'v', 'w', 'x', 'y', 'z']

>>> alpha_ns[2::4]  # Method 1
'cgkosw'

>>> [alpha_lc[i] for i in range(2, len(alpha_lc), 4)]  # Method 2
['c', 'g', 'k', 'o', 's', 'w']

>>> map(chr, range(97, 123))[2::4]  # Method 3 (one-liner)
['c', 'g', 'k', 'o', 's', 'w']

Iterative printing

  • Input:
data = [1,2,3,4,5,6]
  • Methods:
for i,k in zip(data[0::2], data[1::2]):
    print str(i), '+', str(k), '=', str(i+k)
# ~OR~
for i in range(0, len(l), 2):
    print str(l[i]), '+', str(l[i + 1]), '=', str(l[i] + l[i + 1])
  • Output:
1 + 2 = 3
3 + 4 = 7
5 + 6 = 11
  • Other
l = [1,2,3,4,5,6]

>>> zip(l, l[1:])
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]

>>> zip(l, l[1:])[::2]
[(1, 2), (3, 4), (5, 6)]

>>> [a+b for a,b in zip(l, l[1:])[::2]]
[3, 7, 11]

>>> ["%d + %d = %d" % (a, b, a+b) for a,b in zip(l, l[1:])[::2]]
['1 + 2 = 3', '3 + 4 = 7', '5 + 6 = 11']

>>> list = '1234567890'
>>> n = 2
>>> [list[i:i+n] for i in range(0, len(list), n)]
['12', '34', '56', '78', '90']
# The following two accomplish the same thing:
>>> map(''.join, zip(*[iter(list)]*2))
>>> re.findall('..', list)

OS

  • List create a list of the files and directories in the current working directory (pwd):
files = filter(os.path.isfile, os.listdir('.'))
dirs = filter(os.path.isdir, os.listdir('.'))

Miscellaneous

  • Get the current world population estimate (from census.gov):
$ curl -s http://www.census.gov/popclock/data/population/world | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["world"]["population"]'
  • Generate a password hash (change 'password' and 'SALT' values):
$ python -c "import crypt, getpass, pwd; print crypt.crypt('password', '\$6\$SALT\$')"
  • Generate a random password:
$ python -c 'import string,random;print "".join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(16))'