Skip to content

Instantly share code, notes, and snippets.

@hwetsman
Last active January 9, 2022 19:07
Show Gist options
  • Save hwetsman/b71754787e07e5c31cb0f9875a7d432f to your computer and use it in GitHub Desktop.
Save hwetsman/b71754787e07e5c31cb0f9875a7d432f to your computer and use it in GitHub Desktop.
A listing of python syntax

datetime

create datetime object

dt1 = datetime.strptime('20091031','%Y%m%d')

get 'date' object

dt1.date()

get 'time' object

dt1.time()

format datetime to Str

dt1.strftime('%m/%d/%Y %H:%M')

change field value

dt2 = dt1.replace(minute = 0, second = 30)

get difference as a datetime.timedelta object

diff = dt1 - dt2

tuple

create tuple

tup1 = 4, 5, 6 or tup1 = (6,7,8)

create nested tuple

tup1 = (4,5,6), (7,8)

convert sequence to tuple

tup1 = tuple([1,0,2])

concatenate tuples

tup1 + tup2

unpack

a, b, c = tup1

swap variables

b,a = a,b

list

create list

list1 = [1,'a',3] or list1 = list(tup1)

concatenate lists

list1 + list2 or list1.extend(list2) The latter is better as it costs less computationally

append item to list

list1.append('b')

insert to specific position

list1.insert(posIdx,'b') Computationally expensive compared to append

inverse to insert

ValueAtIdx = list1.pop(posIdx)

remove first value from list

list1.remove('a')

check membership

3 in list1 => True Expensive for long lists because it uses linear scan

sort list

list1.sort()

##sort with user supplied function list1.sort(key=len) # sort by length

Slicing

Notation

list1[start:stop] (exclusive of stop) or list1[start:stop:step] if step is used

Take every other step

list1[::2]

Reverse a string

str1[::-1]

Dictionaries

Create

dict1 = {'key1':'value1','key2':'value2'}

create dict from sequence

dict(zip(keyList,valueList))

get an element

dict1['key1'] returns KeyError if key isn't in dict

set an element

dict1['key1'] = newValue

get with default value

dict1.get('key1', defaultValue) returns None if key is not present

check if key exists

'key1' in dict1

delete element

del dict1['key']

get key_list

dict1.keys()

get value_list

dict1.values()

update values

dict1.update(dict2) dict1 values are replaced by dict2

Sets

Create

set([3,6,3]) or {3,6,3}

test subset

set1.issubset(set2)

test superset

set1.issuperset(set2)

test sets have same content

set1 == set2

union (or)

set1 | set2

intersection (and)

set1 & set2

difference

set1 - set2

symmetric difference (xor)

set1 ^ set2

Functions

Definition

def func1(a,b,c=None) where a, b, and c are arguments

Base Types

int

783 0 -192 0b010 (binary) 0o642 (octal) OxF3 (hexa)

float

9.23 0.0 -1.7e-6

bool

True False

str

"One\nTwo" with new line embedded 'I'm' escaped apostrophe """ X\tY|tZ 1\t2\t3""" multiline string

bytes

b"toto\xfe\775" (alpha/hex/octal)

Type Conversion

int('15') 15

int('3f',16) 63 (second parameter is base)

int(15.56) 15

float("-11.24e8") 1124000000.0

bool(x) False for null x, empty container, None or False x; True for other x

str(x) = '...' string of whatever is x

chr(64) '@'

ord('@') 64

repr(x) a literal representation string of x

bytes([72,9,64]) b'H\t@'

list('abc') ['a','b','c']

dict([(3,'three'),(1,'one')]) {1:'one',3:'three'}

set(['one','two']) {'one','two'}

separator str and sequence of str gives assembled str

':'.join(['toto','12','pswd']) 'toto:12:pswd'

str splitted on whitespaces list of str

'words with spaces'.split() ['words','with','spaces']

str splitted on separator str list of str

"1,4,8,2".split(",") ['1','4','8','2']

sequence of one type list of another type via list comprehension

[int(x) for x in ('1','29','-3')] = [1,29,-3]

Containers

ordered sequences

list, tuple, str bytes

key containers

dict, set frozenset is an immutable set keys = hashable values

Get Environmental Variable

import os v = os.environ['VARIABLENAME']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment