niccw
3/6/2019 - 3:13 PM

python_ungrouped

General

String formatting

The new f-strings in Python 3.6 | Seasoned & Agile

# String formatting in python3
print("a={0},b={1}".format(a, b))

# or a newer f method
>>> name = 'Fred'
>>> age = 42
# the f-string can use in other function i.e. console.log too
>>> print(f'He said his name is {name} and he is {age} years old.')
He said his name is Fred and he is 42 years old.

Simplified for loop

matching = [m for m in list if query in m]

Error handling

# try execpt 
try:
    # something may raise error
except KeyError: # if meet KeyError
    # how to handle the error

Check if a variable exisit

python - How do I check if a variable exists? - Stack Overflow

if 'myVar' in locals(): # check if in locals environment (i.e inside function)        

Round decimal number

How do I round to 2 decimals in python? · GitHub

from decimal import Decimal
d = Decimal(0.0005678) # d is a decimal class
d = float(d) # turn it back to float safe (in case other module cannot process decimal type)

Randomly pick from list

import random

foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))

Load module (self defined)

How does python find packages? // Lee On Coding // My blog about coding and stuff.

import imp
# Load the hi module using imp
hi = imp.load_source('hi', my_module_file)

# Now this works, and prints hi!
import hi 
print hi.a # a is 10!
print type(hi) # it's a module!