0% found this document useful (0 votes)
22 views

General Python

This document serves as a comprehensive reference for Python programming, detailing various functions, operators, and error management techniques. It includes information on string manipulation, mathematical operations, decision-making structures, and file handling methods. Additionally, it provides insights into iterable data containers and their associated methods.

Uploaded by

humohit6u
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

General Python

This document serves as a comprehensive reference for Python programming, detailing various functions, operators, and error management techniques. It includes information on string manipulation, mathematical operations, decision-making structures, and file handling methods. Additionally, it provides insights into iterable data containers and their associated methods.

Uploaded by

humohit6u
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

www.wikipython.

com 013022 *in this document the symbol  means yields, results in, or produces
$

vPro2022b © 2022
John A. Oakey
For
3.6+ TOOLBOX 

print() function: default = '\n' slice selection: str[start:stop[:step]]; str to find sub causes ValueError
print(objects, separator="", end='\n') [:stop];  a string created by the selection separator.join([string list])
print("Hello World!") Hello World! String Formatting joins strings in iterable with sep
.format() - char; can be null
Operators method: (1) substitution (2) pure format .partition(sep)  3 tuple: before,
sep, after
Math: =(execute/assign) +; -; *; /; (1) 'string {sub0}{sub1}'.format(0, 1)
[new 3.9] .removeprefix(prefix,/)
** (exp); += a+=b  a=a+b; -=; *=; print("Give {0} a {1}".format('me','kiss')) and .removesuffix(suffix,/)
**=; /=; //= floor div (int with no (2) '{:format_spec}'.format(value)
function: format (value, spec) .replace(old, new[, count]) 
remainder); % (modulo)  remainder substring old replaced by new in object;
from division; value swap a,b=b,a; format_spec: (format mini-language string) if count is given, only the count
Boolean: False, True (0 , 1) [[fill] align] [sign] [# - alt form] [0-forced number of values are replaced
Logical: and, or, not modify compare .rfind(sub[, start[, end]]) 
pad] [width] [,] [.precision] [type]
Comparison: == (same as); != (is lowest index of substring in slice
not equal); <; <=; >; >=; is; is x, fmt = 12345.678, " 10,.2f" see pg 4 [start:end]. -1 on fail
print(Pay $" + format(x, fmt)) or .rindex()rfind but fail  ValueError
not; all  Boolean values — (T/F)
New in 3.6 f-strings format strings .rsplit— like split, except splits
Membership: in; not in; - a list, print(f"Pay ${x:{fmt}}")
tuple, string, dictionary, or set from right
 Pay $ 12,345.68 .split([sep] [maxsplit=])  word
Identity: is; is not the same object .center(width[, fillchar]) string centered in
Binary: & (and); | (or); ^ (xor - 1 list, default sep is space(s)
width area using fill character 'fillchar' .splitlines(keepends=False) 
not both); ~ inversion, = -(x+1); .capitalize() First character capitalized
<< (shift left); >>(shift right) .ljust(width [, fillchar]) or .rjust(same args) .startswith(prefix[,start[,end]]))
bin(0b0101 <<1)  '0b1010' .lower()/.upper()  change case  True/False prefix can be a tuple
Sequence Variable Operators .strip; or .lstrip; or .rstrip; + ([chars])  .translate(table) map to table
strings: + -concatenate, * - repeat; a string with all or leading, or trailing, made with .maketrans(x,[,y[,z]])
single char slice s[i]; range slice s [chars] removed. If [chars] included, all are (maketrans takes/makes strings)
[i:j:k] from, to, step -> start at i, removed. If [chars] omitted or None, the
end j-1, increment by count argument removes whitespace Admin Built-in Functions
.swapcase()  cases exchanged pass (placeholder – no action)
Coding Operators .title()  First Words Capitalized del deletes variables, data containers,
\ Multiline (explicit join) Statements: .zfill(width) - left fill with '0' to len width items in iterables: del mylist[x]
Not needed within [], {}, or () String Methods breakpoint enters debugger - with
; Multiple Statements on a Line: not Str ".is" tests—(Note: tested here for char- wrapper ensures _exit_ method
used/needed with for, if, while acters 0 to 255)  True if all chars in the bool(expression) T/F(F default)
# line comment string meet attribute condition and string callable(object) True if it is
""" block =>1 character in length.  False if Null help(object) invokes built-in help
comment """ system, (for interactive use)
.isalnum()—True if all chars in a string are
either .isalpha(), .isnumeric(), .isdigit() or id(object)  unique identifier
Number Tools .isdecimal() *Note False if your number := (New [3.8]) - assignment
abs(x)  absolute value of x contains a decimal point: to vet a variable expression operator assigns values to
variables inside a larger expression
bin(x) int to binary bin(5)= '0b101' v1 as a float: if (type (v1) == float): or
(a 4, no 2's, a 1); bin(7)[2:] = ‘111’ convert in a try/except structure
divmod(dividend,divisor) from .isalpha()—upper and lower case normal  a new bytearray; source can be an
noncomplex numbers quotient iterable of integers 0 to 255, an integer
letters plus 64 printable characters between defining array size, or a string witn
and remainder tuple chr(170) and chr (255)
float(x)  a floating point number .isdecimal()—digits 0,1,2,3,4,5,6,7,8,9 encoding which will be converted to
from an integer or string; if x=“1.1” bytes using str.encode()
print(float(x)*2) 2.2 .isdigit()—0 to 9 plus superscripts 2 (178), globals()  a dictionary of current
3
hex(x) int to hex string (179), and 1(185) global symbols of the current module
hex(65536)  0x10000 or .isidentifier()—tests a string to see if it is a isinstance(object, classinfo) 
hex(65536)[2:] ‘10000’ valid Python identifier or keyword True if object is an instance of classinfo
oct(x)  integer to octal .islower()—lower case ltrs plus 36 printable issubclass(object, classinfo) 
int(x) characters between chr(170) and chr(255) True if object is a subclass of classinfo
pow(x,y [,z])  x to y, if z is .isnumeric()—.isdigit plus ¼ (188), locals()  a dictionary of the current
present, returns x to y, modulo z ½ (189), and ¾ (190) local symbol table
pow(5,2)=25, pow(5,2,7)=4 .isprintable()—189 of the 256 characters
round(number [,digits]) floating between 0 and 255 starting with the space vars([object])  the __dict__
point number rounded to digits or attribute for a module, class,
chr(32) sequentially to ~ chr(126), then chr instance or object
nearest integer if digits not used (161) to (255) except for chr(173)
round(3.14159, 4)  3.1416
.isspace()—true for chrs (9-13), (28-32),
max, min, sort - see data containers (133) and (160). Note space: " " is chr(32) Looping
None -> constant for null; x=None .istitle()—for all practical purposes, every while (True expression ):
word in a string begins with a capital letter process data statements;
String Tools .isupper()—normal upper case plus 30 [else:] if expression is false, do once
repr(object) printable string printable characters between chr(192-222) for expression to be iterated: usually
ascii(str)  like repr, esc non-ascii .casefold()  casefold - caseless matching with in or range (start, stop [,step])
eval("Python expression str")  value .count(sub[,start[,end]])  # of substrings [else:] executed unless a break
chr(i)  character of Unicode 97= 'a' .encode(encoding="utf-8", errors="strict") statement interrupts execution cycle
input(prompt)  user input as str .endswith (suffix[, start[, end]])  T/F In both for or while loops:
len()  length of str; count of iter- .expandtabs() replace tabs with spaces break ends the innermost loop and
able items (list/dictionary/tuple/set) .find(sub[, start[, end]])  the index of prevents else: from executing,
ord(str) value of Unicode char. substring start, or -1 if it is not found; continue skips to next loop cycle.
str(object) string val of object print(’Python’.find(“th”))  2 *if also supports an else statement and
.index(sub[,start[,end]]) = .find but failure can be confusing if not placed as a peer
www.wikipython.com *in this document the symbol  means yields, results in, or produces
For

vPro2022
© 2022
John A. Oakey
TOOLBOX 3.6+

Decision Making Functions * boldface not in this basic toolbox hasattr()


hash()
list()
locals()
pow()
print()
staticmethod
str()
if elif else: abs() callable() enumerate() help() map() property() sum()
if some True statement: #execute code all() chr() eval() hex() max() range() super()
elif alt True statement: # do this code any() classmethod exec() id() memoryview repr() tuple()
else: # otherwise execute this code ascii() compile() filter() input() min() reversed() type()
bin() complex() float() int() next() round() vars()
Ternary if: an inline if that can be bool() delattr() format() isinstance() object() set() zip()
use in formulas breakpoint() dict() frozenset() issubclass() oct() setattr()
print(x if x in myword else "", end="") bytearray() dir() getattr() iter() open() slice() __import__()
bytes() divmod() globals() len() ord() sorted()

Error Management Errors


ArithmeticError*
EOFError
EnvironmentError
MemoryError
ModuleNotFoundError
TabError
TimeoutError
use in error handling blocks
AssertionError FileExistsError NameError TypeError
try: #code with error potential
except [error type]: #code if any AttributeError FileNotFoundError NotADirectoryError UnboundLocalError
error or a specified error occurs BaseException FloatingPointError NotImplementedError UnicodeDecodeError
else: #otherwise do this code BlockingIOError IOError OSError UnicodeEncodeError
finally: #do this either way BrokenPipeError ImportError OverflowError UnicodeError
assert: condition = False will raise BufferError* IndentationError PermissionError UnicodeTranslateError
an AssertionError BytesWarning IndexError ProcessLookupError ValueError
raise forces a specified, usually ChildProcessError InterruptedError RecursionError WindowsError
custom, exception. Custom errors ConnectionAbortedError IsADirectoryError ReferenceError ZeroDivisionError
are created as their own class. ex: ConnectionError KeyError RuntimeError *non-system-exiting
class TempTooHigh(Error): ConnectionRefusedError KeyboardInterrupt SyntaxError exceptions
'''Arduino input over max range''' ConnectionResetError LookupError* SystemError
pass DeprecationWarning
Helpful definitions: Iterable: an object
File Access and Methods that can return members 1 at a time Iterable Data Container
filepath=r"C:\files\mytest.txt” Mutable: can be changed Immutable: can't Methods & Operations
Python natively handles only strings in files Ordered: held in a fixed sequence Unique:  i,j,k: indexes | x: values/ objects
open(filepath [,mode], buffering]) can not contain any duplicate values
Typical useage: open in with structure: Set concepts and terms: diagram next page L / T / D / S / F / SF  instances of:
list, tuple, dictionary, set, frozen set, both
with open("wholefilepath") [as xfile]:
Unique Data Type Statements/Methods
xfile=mytest.read().splitlines() Universal Iterable Tools
**with structure automatically closes a file LISTS: [ ] - Ordered, Mutable
all(iterable)
Helpful methods: .read(), .read any(iterable)  True if any element is create L=[]; L=[[x[,x]…]]; L=list
(size), .readline(), .readlines(), True *all and any are both FALSE if empty (L/T/S/F); list(D)  list of all diction-
.write(string), .close(), .splitlines del(iterable instance) - delete ary keys; (list(D.values()) for list of values)
([keepends]), list(openfile). enumerate(iterable, start = 0) tuples list L=L2[i:j:k] new list from slice of L2
alist = ['x','y','z']; l1 = list(enumerate(alist)); print(l1) add/remove items L1+L2 concate-
.close() – not needed in with structure
*Many other functions not shown here
 [(0,'x'), (1,'y'), (2,'z')] nate (lists only); .append(x) where x is
File Modes: open for filter(function, iterable) selector for string or data object; .clear() remove
'r' reading (default) elements for which function is True all members; .copy() duplicate list;
'w' writing, truncating the file first iter and next(iterator ,default]) create .extend(iterable) adds iter members;
'x' exclusive creation, fails if it exists iterator with iter; fetch items with next ; strings add letters as members; insert
'a' writing, appending to the end of default returned if iterator exhausted, or (item, position); .pop(i) return and
the file if it exists StopIteration  remove ith item, last item if no i;
'b' binary mode team = ['Amy', 'Bo', 'Cy']; it1 = iter(team); .remove(x) remove first item = x
't' text mode (default) myguy = ""
Amy query L[x]  value at position x, can
'+' for updating (reading and writing), while myguy is not "Cy":
myguy = next(it1, "end")  Bo be multiple values: a,b=L[2:4]; .count
ie. "r+" or "w+" Cy
print(myguy) (x) find number of instances of x in list;
map(function, iterable) can take .index(x[,at/after index i][,before index j])
Object Methods multiple iterables - function must take just as
many
 slice position of string or value x in
Working with object attributes (most list, ValueError if not in found; len(L);
alist=[5,9,13,24]; x = lambda z: (z+2) max(L); min(L); x in L; x not in L
useful for created class objects)
getattr(object, ‘name’ [, default]) list2 = list(map(x, alist)); print(list2) manipulate .sort(key=none/function,
listatr = getattr(list, '__dict__') range ([start,] stop [,step]) reverse=False); sorted(L[,reverse]);
for item in listatr: alist=["Amy","Bo","Cy"] 0 Amy L.reverse() reverse item order;
print(item, listatr[item], sep=" | ") for i in range (0, len(alist)):  12 Bo
Cy
TUPLES: ( ) - Ordered, Immutable
setattr(object, ‘name’, value) print(str(i), alist[i]) # note slice create T=(); T=(x,[[x],(x)…]);
hasattr(object, 'name') reversed() reverse iterator: list or tuple
delattr(object, 'name')
alist=["A","B","C"]; print(alist)
alist.reverse(); print(alist); List Comprehensions
exec(string or code obj[, globals rev_iter = reversed(alist) ['A', 'B', 'C'] Make a new list with exclusions and modifica-
[, locals]]) dynamic code execution for letter in range(0, len(alist)):  ['C', 'B', 'A'] tions from an existing list or tuple: brackets
A, B, C, around the expression, followed by 0 to many
compile(source, filename, mode, print(next(rev_iter), end=", ")
for or if clauses; clauses can be nested:
flags=0, don’t_inherit=False, sum(iterable [, start]) all
optimize=-1) create a code object that numeric new_list = [(modified)item for item in old_list if
exec() or eval() can execute ex: if a=[8,7,9] then sum(a)  24 some-item-a ribute of (item)]
hash(object)  integer hash value if type([iterable])  object datatype atuple=(1,-2,3,-4,5)
available zip() creates aggregating iterator from mylist=[item*2 for item in atuple if item>0]
multiple iterables,  iterator of tuples of ith print(atuple, mylist)
dir()  names in current local scope  (1, -2, 3, -4, 5) [2, 6, 10]
iterable elements from each sequence or
dir(object) valid object attributes iterable. if modifying items only: up1list =[x+1 for x in L]
www.wikipython.com *in this document the symbol  means yields, results in, or produces
For

vPro2022
© 2022
John A. Oakey
TOOLBOX 3.6+

TUPLES: (continued from pg 2 ) S.intersection_update CLASS - an object blueprint


T= tuple(T/L/S/F) or S1 &= S2; Keep universal elements. (required in red, optional in green)
add members +=(x,[x]) add 1 or S.difference_update(iterable) or S1 -= Common components of a class include:
more items, note comma for 1 item; S2 Remove members found in others. 1 *inheritance creates a “derived class”
T1 + T2 concatenate (tuples only) S.symmetric_difference_update(iterable) command key word colon 
query =T[i:j] get slice values, j is last S1 ^= S2; keep unique elements only class class-name (inheritance):
item + 1; .count(x) find number of your class name class definition header
Class creates a namespace and provides
instances of x in tuple; T.index(x[,at/ instantiation and attribute references
after index i][,before index j])  slice 2 a docstring, ’’’Docstring example”’
position of possible member x,; min(T); 3 instantiation with special method:
max(T); len(T); x in T; x not in T def __init__(self, arguments):
manipulate sorted (T, reverse=T/F); ~ autoinvoked when class is created;
T[::-1] reverse order ~ arguments are passed when a class
instantiation is called.
~ Includes variable name assignments, etc.
DICTIONARIES: { } Mutable, Unordered, *4 function definitions and local
Unique keys k  'key', v  'value' variable assignments
create D={k:v, [,k:v]}; =dict(i=j  class mammalia(object):
[,k=l]); =dict(zip(L1, L2)); D2=  "A class for mammal classification"
 def __init__(self, order, example):
D1.copy(); =dict.fromkeys (L/T/F ,

Example
self.ord = order
pair members with v/None/ iterable); self.ex = example
self.cls="mammal"
add/remove members  def printInfo(self):
D[k]=new_value; D.update(D2) add D2 info="class/order: " + self.cls + "/"+\
items to D replacing dup values; D=(**D| self.ord +", Example:" + self.ex
**D2); D.setdefault(k[,default]) print(info)
mam_instance = mammalia("cetacea","whales")
return value if k in dict, if not, insert and mam_instance.printInfo()
return default; D.clear(); del D[k] remove */** for iterable (argument) unpack  class/order: mammal/cetacea,
member; D.pop(k)  v and removes k; * for list & tuples: Ex: a,*b,c = [1,2,3,4,5] Example: whales
new [3.9]: D=D2|D3; D|=k/v pairs;  a=1, c=5, b=[2,3,4]
query x=D[k]  v or keyerror if no k; ** for dictionaries *args and *kwargs
x=D.get(k[,x]) like D[k] but  x if no k; d1={1:'a', 2:'b'}; d2={2:'c', 3:'d'} ; used to pass an unknown
len(D); Dictionary views: D.keys(), d1={**d1, **d2} or new in [3.9] d1|=d2 number of arguments to arg#1: B
 d1={1:'a',2:'c',3:'d'} a function. arg#2 is C
D.values(), D.items() for items view,
x  a list of key:value tuples; all views
*args is a list
def testargs (a1, *argv):
 arg#3 is T
arg#4 is A
can all be iterated User Functions print('arg#1: ', a1)
for ax in range(0, len(argv)):
x in D.view; x not in D.view; def - command to create a user function print ("arg#"+str(ax+2)+" is "+argv[ax])
manipulate D[existing k]=value testargs('B', 'C', 'T', 'A')
change value; [new in 3.8] where ri is a def func on_name (args or kwargs):  *kwargs is a keyword -> value pair
reversed iterator ri=reversed(D.view) return(variable object) return the keyword is not an expression
iterate with next(ri); sorted(D.items()) value(s) that a function derived - or - def testkwargs(arg1, **kwargs):
formal arg: 1
print ("formal arg:", arg1)
Use enumerate to make a dictionary. ex: mydict = dict(enumerate(mylist))
yield/next in a generator function, yeild for key in kwargs:
('dog', 'cat')
returns a sequential value incremented print ((key, kwargs[key]))
('arg2', 'two')
SETS: Unique, Mutable, Unordered by next after the function call (see below) testkwargs(arg1=1, arg2="two", dog='cat')
create S={x,x,x}; S=set(L/T/F); global x creates global variable - Example of: func on, *, *args
S=’string'  unique letters defined inside a function def myfunc(*args): # function unknown # args
FROZENSETS: immutable after creation; nonlocal makes a variable in a nested print(*args)
create F=frozenset([iterable]) * only function valid in an outer function my_list = ['a1','b2','x','c3'] # create list
myfunc(*my_list) # new list expanding old
Set & Frozenset Creating a Function del my_list[2] # remove 2nd item
Methods and Operations (required in red, optional in green) myfunc(*my_list) # reprint to prove
SF.copy() Return a shallow copy. command key word arguments
SF.symmetric_difference(SF2) or SF^SF2 *1 def name (input or defined params): NEW IN 3.10
elements in either, not both
SF.union(SF2) or SF3=SF1 | SF2[|...]
 new function name colon Case Pattern Matching
[ *2 """a docstring""" (can be multiline) ] "Takes an expression and compares
merge the sets *next segment code block its value to successive patterns given
SF.intersection (SF2) or SF1 & SF2 *last segment return(value to pass back) in one or more case blocks."
intersection of S1 & S2 or a generator passed using yield: match value | string | list | T/F:
SF.difference(S2) or SF-SF2 unique in SF vowels, myword = 'aeiouy','idea' case value | string | list | T/F:
query (Sets & Frozensets) len(SF); def gen1(wordin): <responding code>
 aei
Example

Boolean Tests: x in SF; x not in SF; for letter in wordin: case…


SF.isdisjoint(SF2) T if no common items yield(letter) case _: # nothing matched must
SF.issubset(SF2) & SF1<=SF2 One set for letter in gen1(vowels): be the last case match
print(letter if letter in myword else "")
is contained by the other. next
~ case can match multiple objects
SF1<SF2 set is a proper subset ~ a list case object can be unpacked *
SF1.issuperset(SF2) or SF1=>SF2 Lambda: an unnamed inline function case ["paint", *colors]:
Every element of SF1 in SF2 lambda [parameter(s)]: expression for color in colors ….. etc.
SF1>SF2 set is a proper superset z = lambda x: format(x**3,",.2f"); ~ can capture subpattern using or/as
print(z(52.1))  141,420.76 case [x, (1 | 3 | 5 | 7) as choice]:
Sets ONLY add/remove members
S.remove(element) Key Error if missing;
S.discard(element) no error if missing;
S.pop() remove/return random
element; S.clear(); S.add(i); in; not
in;
S.update(iterable); or S1 |= S2; These
add members from iterable(s) or set(s).
www.wikipython.com *in this document the symbol  means yields, results in, or produces
For

vPro2022
© 2022
John A. Oakey
TOOLBOX 3.6+

f-string Formatting Bytes and Bytearray Built-in Types numerics, sequences, mappings,
[new 3.6] Operations classes, instances, exceptions
Conversion Types x. = method can be used w/
'd' Signed integer decimal. Numeric Types
"bytes." or "bytearray." int, float, complex constructors:
'i' Signed integer decimal. i.e.,
'o' Signed octal value. complex(real, imaginary) imaginary defaults to 0
x.count(sub[, start[, end]])
'u' Obsolete type – it is is same as bytes.count(sub Numeric Operations
identical to 'd'. [, start[, end]]) or x+y sum of x and y x-y difference of x and y
'x' Signed hexadecimal bytearray.count(sub[, start x*y product of x and y x/y quotient of x and y
(lowercase). [, end]]) x // y floored quotient of x and y
'X' Signed hexadecimal x%y remainder of x / y -x x negated
x.decode(encoding="utf- +x x unchanged abs(x) absolute value x
(uppercase), 8", errors="strict")
'e' Floating point exponential int(x) x converted to integer
x.endswith(suffix[,start[, end]]) float(x) x converted to floating point
format (lowercase). x.find(sub[, start[, end]])
'E' Floating point exponential complex (real, imaginary) imaginary defaults to 0
x.index(sub[, start[, end]]) c.conjugate() conjugate of complex number c
format (uppercase). x.join(iterable) divmod(x, y) the pair (x // y, x % y)
'f' Floating point decimal static bytes.maketrans pow(x, y) x to the power y
format. (from, to) x ** y x to the power y
'F' Floating point decimal static bytearray.maketrans round(x[,n]) round to n digits, half to even
format. (from, to) math module (import math) adds
'g' Floating point format. Uses x.partition(sep) these rounding operations: Escape Codes
lowercase exponential x.replace(old, new[, count]) math.trunc(x); math.floor(x); \n newline
format if exponent is less x.rfind(sub[, start[, end]]) math.ceil(x) \t tab
than -4 or not less than x.rindex(sub[, start[, end]]) Sequence Operations \\ backslash
precision, decimal x.rpartition(sep) x in s True if an item of s is equal to x \' \"quote sgl/db
otherwise x.startswith(prefix[, start x not in s False if an item of s == x \a ascii bell
'G' Floating point format. Uses s+t the concatenation of s and t \000 octal val
[, end]]) 000
upper-case exponential x.translate(table,/,delete=b) s * n or n * s concatenate s n times
s[i] ith item of s, origin 0 \xhh hex val hh
format if exponent is less x.center(width[, fillbyte]) \r carriage return
s[i:j] slice of s from i to j
than -4 or not less than x.ljust(width[, fillbyte]) s[i:j:k] slice of s from i to j step k
precision, decimal format x.lstrip([chars]) len(s) length of s
otherwise. x.rjust(width[, fillbyte]) min(s) smallest item of s
'c' Single character - accepts x.rsplit max(s) largest item of s
integer or single character (sep=None, maxsplit=-1) s.index(x[, i[, j]]) index of the first occurrence of x in s (at
str x.rstrip([chars]) or after index i and before index j)
'r' String - uses repr() to x.split(sep=None, maxsplit= s.count(x) number of occurrences of x in s
convert object -1) Mutable Sequence Operations
's' String - uses str() to x.strip([chars]) s[i] = x item i of s is replaced by x
convert object x.capitalize() s[i:j] = t slice of s from i to j is replaced by the contents
'a' String - uses ascii() to x.expandtabs(tabsize=8) of the iterable t
convert object x.isalnum() del s[i:j] removes i to j; same as s[i:j] = []
'%' Puts '%' character before x.isascii() s[i:j:k] = t the elements of s[i:j:k] are replaced by those of
x.isalpha() t; start, stop, step
result del s[i:j:k] removes the elements of s[i:j:k] from the list
conversion flags x.isdigit() s.append(x) appends x to the end of the sequence
'#' conversion will use x.islower() s.clear() removes all items from s (same as del[:])
“alternate form” x.isspace() s.copy() creates a shallow copy of s (same as s[:])
'0' conversion zero padded for x.istitle() s.extend(t) or s += extends s with the contents of t (for the most part
numerics x.isupper() the same as[len(s):len(s)] = t)
'-' value is left adjusted x.lower()x.splitlines s *= n updates s with its contents repeated n times
(overrides '0' ) (keepends=False) s.insert(i, x) inserts x into s at the index given by i(same as s[i:i] = [x])
' ' (space) Leave a space x.swapcase() s.pop([i]) retrieves the item at i and removes it from s
x.title() x.upper() s.remove(x) remove the first item from s where s[i]== x
before a + or # s.reverse() reverses the items of s in place
'+' A sign character ('+' or '-') x.zfill(width) ** see: https://docs.python.org/3.10/library/stdtypes.html
will precede conversion
(overrides “space” flag). Operators and
Precedence Keywords (reserved)
Integer Bitwise lambda and, as, assert, async, await, break, class,
Operations if – else continue, def, del, elif, else, except, False,
Operation / Result or · and · not x (Boolean) finally, for, from, global, if, import, in, is,
x|y in · not in · is · is not lambda, nonlocal, None, not, or, pass, raise,
bitwise or of x and y < · <= · > · >= · != · ==
|·^·& bitwise OR, XOR, AND return, True, try, while, with, yield
x^y << · >> Built-in Constants
bitwise exclusive or x and y +·- False, True, None, NotImplemented, Ellipsis (same
x&y * · @ · / · // · % (multiply, as literal '…'), __debug__, quit(), exit(), copyright,
bitwise and of x and Y matrix multiply, division, floor credits, license
x << n divison, remainder)
x shifted left by n bits +x · -x · ~x (pos, neg,
x >> n bitwise NOT) Boolean Operations
x shifted right by n bits ** (exponentiation) Operation / Result (ascending)
~x await (Await expression)
x[index] · x[index:index] · x or y if x is false, then y, else x
the bits of x inverted x(arguments...) · x and y if x is false, then x, else y
x.attribute (subscription, not x if x is false, True, else False
www.wikipython.com slicing, call, attribute ref)
www.wikipython.com *in this document the symbol  means yields, results in, or produces
For

vPro2022 © 2022
John A. Oakey
TOOLBOX 3.6+


The Python Standard Library modules including: Development Tools – 9 modules:


Content: docs.python.org/3/py-modindex.html zipfile — Work with ZIP archives Debugging and Profiling – 7 modules:
Text Processing Services - 7 modules tarfile — Read and write tar archive files Software Packaging and Distribution – 4
including: File Formats – 5 modules including: modules NOTE: distutils deprecated -
string — Common string operations csv — CSV File Reading and Writing Setuptools now includes it
re — Regular expression operations Cryptographic Services – 3 modules: ensurepip — bootstrapping pip installer
textwrap — Text wrapping and filling Generic Operating System Services – 16 Python Runtime Services – 14 modules
Binary Data Services - 2 modules modules inc: including:
Data Types – 13 modules including: os — Miscellaneous operating system sys — System-specific parameters and
datetime — Basic date and time types interfaces functions
calendar — Calendar-related functions time — Time access and conversions sysconfig — Access to Python’s config
copy — Shallow and deep copies io — Core tools working with streams information
enum — Support for enumerations platform — Accesss to platform identifying __main__Top-level script environ.
pprint — Data pretty printer data inspect — Inspect live objects
Numeric and Mathematical Modules – 7 Concurrent Execution – 10 modules Custom Python Interpreters – 2 mods
modules including: including: Importing Modules – 5 modules including
numbers — Abstract base classes threading — Thread-based parallelism zipimport — Import modules from Zip
math — Mathematical functions multiprocessing — Process-based archives
cmath - complex #; decimal - accurate parallelism runpy — Locating and executing Python
random — Generate pseudo-random #s Interprocess Communication and modules
statistics — Statistical functions Networking - 9 mods Internet Data Python Language Services – 13 mods :
fractions — Rational numbers Handling – 10 modules: keyword — Testing for Py keywords
Functional Programming – 3 modules Structured Markup Processing Tools – py_compile — Compile Python source
File and Directory Access – 11 modules 13 modules: files
including: Internet Protocols and Support - 21 Miscellaneous Services – 1 module:
pathlib — Object-oriented file paths modules MS Windows Specific Services – 4
os.path — Common path functions Multimedia Services – 9 modules modules
fileinput — iterate lines—multiple inputs including: Unix Specific Services - 13 modules:
filecmp — File and directory compare wave — Read and write WAV files Superseded Modules – 2;
shutil — High-level file operations Internationalization – 2 modules: Undocumented Modules – 1
Data Persistence – 6 modules including: Program Frameworks – 3 modules pypi.org another 257M+ modules
pickle — Python object serialization including: including: RPI.GPIO, Pillow, pandas,
marshal — Internal Python object turtle — Turtle graphics fuzzywuzzy, Anaconda, miniconda, conda,
serialization Graphical User Interfaces with Tk – 6 playsound, Poetry, Numpy, etc.
sqlite3 — DB-API 2.0 interface for SQLite modules including: To find installed modules from Python:
databases tkinter — Python interface to Tcl/Tk >>> help('modules')
Data Compression and Archiving – 6 IDLE

Selected Standard Library Module Constants and Methods for New Users
calendar import calendar backup="", *, mode='r', openhook=None) if a & b are close, otherwise False, relative or abs
a couple of fun examples: .filename()  file being read tolerance
c=calendar.TextCalendar(calendar.SUNDAY) .fileno()  file descriptor (-1 is none open) .isfinite(x) True if x not infinity or a NaN
c.pryear(2021,w=2,l=1,c=6,m=3) or try .lineno() cumlatiave # of last line read .isinf(x) True if x is a positive or negative infinity
c=calendar.TextCalendar(calendar.MONDAY) .filelineno()  line # in current math.isnan(x)  True if x is a NaN (not a
c.setfirstweekday(calendar.SUNDAY) .isfirstline()  True if first line of its file number), False otherwise.
print(c.formatmonth(2021,1,w=0,l=0)) .isstdin()  True if last line was read [new 3.8] .isqrt(n) the integer square root of the
many functions - see: www.wikipython.com -> from sys.stdin nonnegative integer n. This is the floor of the exact
OTHER MODULES -> calendar .nextfile() close file, read next line from next file square root of n, or equivalently the greatest
cmath - A suite of functions for complex # .close() close integer such that a² ≤ n. To compute the ceiling of
fractions.py import fractions the exact square root of n, a positive number, use
copy - import copy relevant for compound a = 1+ isqrt(n - 1).
objects, (objects containing other objects) .Fraction (numerator=0, denominator=1)
.Fraction(other_fraction) .ldexp(x, i)  x * (2**i); inverse of frexp()
.copy(x) <-relies on references to objects .modf(x)  fractional and integer parts of x
.deepcopy(x[, memo]) <-copies objects (so you .trunc(x) Real value of x truncated to integral
can change the copy and not the original) a= '3.03125' ; print(fractions.Fraction(a))
print(fractions.Fraction(3.14159)) .exp(x)  e**x. .expm1(x)  e**x - 1
csv See Data on Disk Toolbox .log(x[, base]) 1 argument,  natural logarithm of
 3537115888337719 / 1125899906842624
datetime from datetime import * x (to base e). 2 arguments,  the logarithm of x to
idlelib IDLE is Python's native IDE see:
hundreds of functions and attributes the given base, calculated as log(x)/log(base).
h ps://docs.python.org/3.10/library/idle.html .log1p(x)  the natural logarithm of 1+x (base e).
today = date.today()
decimal fast, correctly rounded fp math with a io import io: three types: text, binary, raw Ex: accurate for x near zero
f = open("myfile.txt", "r", encoding="utf-8") .log2(x)  the base-2 logarithm of x
gazillion functions and pages of instruction
f = open("myfile.jpg", "rb") .log10(x)  base 10 log of x
ensurepip - boostrap pip into an existing f = open("myfile.jpg", "rb", buffering=0) .pow(x,y)  x raised to y
Python environment - pip is the installer for json - See Data on Disk Toolbox .sqrt(x)  square root of x
modules not in the Standard Library Trigonometric Functions: radians .atan2(y,x)
Windows command line invocation: math - import math functions include:
.ceil(x) smallest int >= x .hypot(x,y)  sqrt(x*x + y*y) .acos(x) .asin(x)
python –m ensurepip -- upgrade .atan(x) .cos(x) .sin(x) .tan(x)
.comb(n,k) ways to choose k items from n
enum - from enum import enum .copysign(x,y) absolute value of x, sign of y .degrees(x) anglex from radians to degrees
mimicks enum in C, fast integer access and iter. .radians(x) anglex from degrees to radians
.fabs(x) absolute value of x
filecmp import filecmp .factorial(x)  x factorial as integer math.pi π = 3.141592… math.e e = 2.718281…
.cmp(f1, f2, shallow=True) Compare f1 and f2, .floor(x)  largest int <= x math.nan A floating-point “not a number” (NaN)
returning True if they seem equal .fmod(x,y) mathematically precise ver of x%y numbers - operations from abstract base
fileinput import fileinput .frexp(x)  mantissa and exponent of x (m,e) classes - four classes defined: Complex(compon-
for line in fileinput.input(): .fsum(iterable) returns fp sum of values ents: real, imaginary), Real, Rational (adds
your code to process(line) .gcd(a,b) greatest common divisor of a & b numerator and denominator properties), Integral
.input (files=None, inplace= False, .isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) True os import os **hundreds of functions, many
www.wikipython.com *in this document the symbol  means yields, results in, or produces
For

vPro2022
© 2022
John A. Oakey
TOOLBOX 3.6+

os specific; a few universal .uniform(a, b) a float between a and b time.sleep(seconds) # delay of five seconds
.environ['HOME'] home directory, re import re complex search and match print(time.asctime(time.localtime()))
.chdir(path) change working dir re.search(pattern, string, flags=0) Mon Aug 3 16:22:31 2020
.getcwd() current working dir re.match(pattern, string, flags=0) print(time.ctime(mytime))
.listdir(path) .mkdir(path) .mkdirs(path) re.ignorecase Mon Aug 3 16:22:26 2020
make all intermediate directories .remove(path) shutil import shutil tkinter from tkinter import * a 16 page
.strerror() translate error code to message .copyfileobj(fsrc, fdst[, length]) tkinter Toolbox is available for review at
.curdir() .rename(src, dst) .rmdir(path) .copyfile(src, dst, *, follow_symlinks=True) www.wikipython.com—free download on GitHub
.walk(start directory, topdown=True) produces a .copymode(src, dst, *, follow_symlinks=True) a better (?) option : see PySimpleGUI below
generator of filenames in a directory tree Copy the permission bits from src to dst.
.system(command) Unix and Windows, execute .copystat(src, dst, *, follow_symlinks=True) A Few PyPi Modules
the command in a subshell Copy the permission bits, last access time, last https://pypi.org
os.path Lib/posisxpath or Lib/ntpath (windows) modification time, and flags from src to dst Anaconda, Conda, MiniConda - 3 related
import os.path [as osp] .copy(src, dst, *, follow_symlinks=True) programs offering environment management at
.abspath(path) normalized absolutized version of Copies the file src to the file or directory dst. src
different levels. Anaconda manages all variations
the pathname path. and dst should be strings.
and compatibility issues unavoidable with many
.basename(path) base name of pathname path. .copy2(src, dst, *, follow_symlinks=True)
modules. Over 300 applications come "installed" in
.commonpath(paths) longest common sub- copy2() also attempts to preserve file metadata
the base (root) environment, with thousands
path.commonprefix(list)  the longest prefix .copytree(src, dst, symlinks=False, ignore=None,
available. Installation(s) can be huge. It qualifies
.dirname(path)  directory name of path copy_function=copy2, ignore_dangling_symlinks=
as a language within itself. Numerous IDEs are
.expandvars(path)  environment variables expanded False, dirs_exist_ok=False) available in any Anaconda environment including
.exists(path)  True if path exists .disk_usage(path)  disk usage stats as tuple Spyder, Visual Studio Code, IDLE, Jupyter
.getsize(path) n the size, in bytes, of path. (total, used and free) in bytes—a file or a directory
Notebooks ... more. Miniconda is a lightweight
.isabs(path) True if path is absolute pathname Sound if your objective is to play a sound using a version. Conda is similar to pip but is also an
.isfile(path)  True if path is existing file Python Standard Library module save your time - environment manager.
.isdir(path)  True if path is existing directory none of the modules listed under Multimedia
.islink(path) True if ref is an existing directory Services do that. SEE: PyPi — playsound
NumPy - powerful N-dimension array objects
.join(path, *paths) Join one or more path NumPy says installation works best with a prebuilt
sqlite3 See Data on Disk Toolbox package, see: https://scipy.org/install.html where
components intelligently. statistics import statistics
.normcase(path) Normalize case of a pathname they suggest a "scientific distribution" but do give
.mean(data) average pip directions
.normpath(path) On Windows, converts forward
slashes / to backward slashes \. .harmonic_mean(data) harmonic mean Rpi.GPIO – module to control Raspberry Pi
.relpath(path, start=os.curdir)  relative filepath .median(data) middle value GPIO channels; see GPIO toolbox and download
from the current directory or an optional start .median_low(data) low middle value link at: www.wikipython.com
.samefile(path1, path2)  True if both pathname .median_high(data) high middle value
.median_grouped(data) 50th percentile
Pillow - by Alex Clark, updated Aug 2020, a friendly
arguments refer to the same file or directory. version of Fredrik Lundh's Python Imaging Library
.mode(data) most common
.sameopenfile(fp1\fp2)  True if the same Pillow version 7.2 works in Python 3.5 to 3.8
.pstdev(data,mu=None) population std dev install: python3 -m pip install --upgrade Pillow
.samestat(stat1, stat2) Return True if the stat
.pvariance(data,mu=None) pop variance from PIL import Image
tuples stat1 and stat2 refer to the same file.
.stdev(data, xbar=None) sample std dev im = Image.open(testfilepath)
.split(path) Split path into a pair, (head, tail)
.variance(data, xbar=None) sample variance print(im.format, im.size, im.mode)
pathlib (3.5) from pathlib import Path [as pt] more...extensive normal distribution functions im.show()
SEE DATA ON DISK TOOLBOX—this is now string
THE critical file access module
PySimpleGUI for high production in a
string.ascii_letters, reasonable time frame PySimpleGUI—a wrapper
pickle import pickle - non-human-readable
Constants

string.ascii_lowercase string.ascii_uppercase for tkinter and other platforms—is simply a better


See Data on Disk Toolbox string. digits string.hexdigits mousetrap. It powerfully trivializes GUI
platform import platform string.octdigits string.punctuation development for programmers who do not want to
.machine()  machine type string.printable string.whitespace specialize in just the graphics of API design.
.node()  network name string.capwords(str, sep=None) playsound is a cross platform program pulled
.processor()  real processor name sys import sys mostly advanced functions from Pypi that is very easy to use. From windows:
.python_version version as string .exit([arg]) - exit python; .getwindowsversion() python -m pip install playsound for example:
.system()  'Linux', 'Darwin', 'Java', 'Windows' .path - search paths list; .version - Python version from playsound import playsound
pprint import pprint tarfile import tarfile extensive archive testwave = "C:\\Windows\\Media\\Alarm09.wav"
allows output of objects, including objects holding including gzip, bz2 and lzma compression playsound(testwave)
other objects in a reasonably readable format. ex: (assumes import tarfile – to extract to cwd) pandas for tabular data — "aims to be the funda-
Begin by creating an instance: (assume "mylist") tar = tarfile.open("sample.tar.gz") mental" module for "real world data analysis" - it is
pp = pprint.PrettyPrinter(indent=3) set indent tar.extractall() ; tar.close() part of the Anaconda distribution (also installs with
then use your instance ("pp" above) to output:
pp.pprint(mylist) textwrap import textwrap Miniconda) but can be installed with pip:
some PrettyPrinter objects new/changed in [3.8] textwrap.wrap(text,width=x,**kwargs)Lib/Lib/ pip install pandas plotly.express and
.pformat(obj), .pprint(obj), pp.isreadable(obj), more time import time or from time import Kaleido - plotly.express is built-in to the plotly
ex: print(pp.isreadable(mylist)) a new user must understand terminology found at: library and is considered a "starting point" but may
py_compile.py import py_compile h ps://docs.python.org/3.8/library/ me.html be all you ever need. Plotly is an MIT Licensed
.compile(file) - the compiled file is placed on file module. plotly.express requires a determined effort
print(time.time()) #seconds since the epoch
to learn because it creates more than 35 types of
path in added directory "/__pycache__/ "  1596486146.111275
graph images. It does not export your graph as a
random import random mytime = time.time() #capture it
static image—which is why you need Kaleido.
only for non-cryptographic applications print(time.localtime(mytime)) #demo the tuple
plotly has many dependencies, kaleido has none.
.seed initialize the random number generator time.struct_time(tm_year=2020,
pip install kaleido.
.getstate() ret object with internal generator state tm_mon=8, tm_mday=3, tm_hour=16, tm_min=22,
.setstate() restores internal state to getstate value tm_sec=26, tm_wday=0, tm_yday=216, Module Management
.getrandbits(k) ret integer with k random bits tm_isdst=1) import get module, ex: import math or
For integers: .randrange(start, stop[, step]) time_tuple=time.localtime(mytime) #capture it from module import *
a random integer N print("The hour is: " + str(time_tuple[3])) #demo from get a single module function: from
such that a <= N <= b. Alias for randrange(a, b+1). The hour is: 16 math import cos; print (cos(9))
For sequences: print(time.strftime("%a, %d %b %Y %H:%M:%S as creates an alias for a function
.choice(sequence) random element +0000", time.gmtime())) What is NOT mentioned in this General Toolbox?
.random()  the next random floating point Mon, 03 Aug 2020 20:22:26 +0000 About 99.83% of Python capability now available
number in the range (0.0, 1.0). seconds=5 ; print("Wait 5 seconds!") has no mention in this toolbox. Happy Coding!

You might also like