Convert String to a Number
# -------------------------------------------------------------------
# ---- Function: convert a string to a float
# -------------------------------------------------------------------
def is_float(s):
try:
n = float(s)
return (True,n)
except:
return (False,0.0)
# -------------------------------------------------------------------
# ---- Function: convert a string to an integer
# -------------------------------------------------------------------
def is_int(s):
try:
n = int(s)
return (True,n)
except:
return (False,0)
def is_integer(s):
return is_int(s)
# -------------------------------------------------------------------
# ---- is a number (integer, float, scientific notation)
# -------------------------------------------------------------------
def is_a_number(s):
tf,n = is_int(s)
if tf:
return True
tf,n = is_float(s)
if tf:
return True
return False
Create 1D and 2D arrays (lists)
# ---- create a 1D array initialized to 99
arr = [99 for i in range(cols)]
or
arr = [99]*cols
or
# ---- initialize to different values
a = [0,1,2,3,4]
arr = [a[i] for i in range(3)]
# ---- create a 2D array (rows,cols) initialized to -1
# ---- with independent column lists (arrays)
arr = [[-1 for i in range(cols)] for j in range(rows)]
# ---- demonstrate independent column lists (different IDs)
for row in range(rows):
print(id(arr[row]))
RegExp - String match RegExp?
# ----------------------------------------------------------------------
# test if a string matches one of a list or tuple of regular expressions
#
# Regular expressions use the backslash character ('\') to indicate
# special forms or to allow special characters to be used without
# invoking their special meaning. This collides with Python's usage
# of the same character for the same purpose in string literals. The
# solution is to use Python's raw string notation for regular
# expression patterns. Backslashes are not handled in any special
# way in a string literal prefixed with 'r'. r"\n" is a
# two-character string containing '\' and 'n'.
# (from Python documentation)
#
# For example to match html files: r'\.html$' or '\\.html$'
# ----------------------------------------------------------------------
import re
def StringMatchPattern(patterns,str):
for p in patterns:
if re.search(p,str,re.IGNORECASE):
return True
return False
MATCHPATTERNS = [ r'\.html$', r'\.pdf$', r'\.png$', r'\.txt$', r'\.css$', r'^xyz' ]
if StringMatchPattern(MATCHPATTERNS,"xyz.txt")
print("Matched Pattern")
Read a file
# read the file one line at a time
with open('Peter_Jones.md','r') as f:
for line in f:
line = line.strip()
print(line)
# read the whole file
f = open("Tom_Jones.md", "r")
print(f.read())
f.close()
# read the file 24 bytes at a time
with open("Judy_Jones.md", "r") as f:
print(f.read(24))
# read the file 1 byte at a time using a generator
def read_bytes(fobj,nbytes):
while True:
byt = fobj.read(nbytes)
if not byt: return
yield byt
with open('Mary_Jones.md','r') as fobj:
for c in read_bytes(fobj,1):
print(c)
Write a file
# 'with' has the advantage that the file is closed, even if an exception is raised
data = ['one','two','three','four']
lc = 0
with open(outfile,'w') as fout:
for s in data:
fout.write(s + '\n')
lc += 1
print(f'{lc} lines written to file {outfile}')
outFile = open('sample.txt','w')
for i in range(10):
outFile.write('Line number {}\n'.format(i))
outFile.close()
RegExp - Replace a Sub-String
# Python Doc: re.sub(pattern,repl,string,count=0,flags=0)
# (if no match is found, the input string is returned)
import re
s0 = 'abc_data.dat'
s1 = re.sub(r'_data','',s0,flags=re.IGNORECASE)
s2 = re.sub(r'\.dat$','.txt',s1,flags=re.IGNORECASE)
s3 = s2.lower()
print(s3)
Note: see regexp02.py code example
Create multiple dirs at one time
this code assumes "if path exists it is a directory"
import os
def MakeDirs(path):
if not os.path.isdir(path):
##print("Creating new directories")
##print("path: {}".format(path))
os.makedirs(path)
else:
##print("Directories already exist")
##print("path: {}".format(path))
return True
path = "./x/x/x"
MakeDirs(path)
this code does not assume "if path exists it is a directory"
import os
def MakeDirs(path):
if os.path.exists(path):
if not os.path.isdir(path)
return False
else:
os.makedirs(path)
return True
Notes:
1. see os.path.normpath documentation
(
os.path - Common pathname manipulations)
New Dictionary - Switch Keys and Values
# ===============================================================
# Reverse keys and Values (duplicates will be lost)
# ===============================================================
# ---- test dictionary
dct = { 'aa':2, 'b':3, 'd':0, 'e':20, 'a':2, 'dd':9 }
print()
print(dct)
# ---- one way
new_dct_1 = dict(sorted(dct.items(), key=lambda item: item[1]))
print()
print(new_dct_1)
# ---- another slightly different way
new_dct_2 = {w:dct[w] for w in sorted(dct,key=dct.get,reverse=True)}
print()
print(new_dct_2)
Ask the user to make a selection (Menu)
# -------------------------------------------------------------------
# ask user to make a selection
#
# Note: regexp should be a raw string
# for example: AskUserToSelect(slist,r'\.py$')
# -------------------------------------------------------------------
def AskUserToSelect(stitle,slist):
l = len(slist)
max = 30
if l > max:
print('')
print('Error: Selection list is to long')
print('len = {} - returning \'\''.format(max))
return ''
while True:
# --- display list menu
ClearScreen()
print('==================================================')
print(stitle)
print('==================================================')
print('## File')
print('-- ---------------------------------------------')
i = 0
while i << l:
print(' {} {}'.format(i,slist[i]))
i += 1
# --- ask the user to select
print('')
sel = GetUserInput('Enter index of selection: ')
# --- valid selection?
if sel == '': # no selection?
return('')
if sel.isdigit() != True:
print('')
print('Illegal selection entered ({})'
.format(sel))
Pause()
continue
idx = int(sel)
if idx < 0 or idx >= l:
print('')
print('Selection out of range ({})'
.format(idx))
Pause()
continue
break
# --- return selection
return slist[idx]
title = "Select a Vacation Tour"
selections = [ "England - Lake Country",
"France - Wine Country",
"Africa - Safari",
"Japan - Shrines",
"India - Taj Mahal",
"None" ]
selection = AskUserToSelect(title,selections)
Resize and display an image using PySimpleGUI
#!/usr/bin/python3
# ===================================================================
# Resize and display an image using PySimpleGUI
# -------------------------------------------------------------------
# also try sg.Image('image file',size=(300,300))
# -------------------------------------------------------------------
# From: stackoverflow.com/questions/67079155/displaying-an-image-
# using-pysimplegui-without-having-to-use-an-event-listener
# ===================================================================
from PIL import Image, ImageTk
import PySimpleGUI as sg
filename = 'example.png'
# ---- Resize PNG file to size (300, 300)
size = (300, 300)
im = Image.open(filename)
im = im.resize(size, resample=Image.BICUBIC)
sg.theme('DarkGreen3')
layout = [
[sg.Image(size=(300, 300), key='-IMAGE-')],
]
window = sg.Window('Window Title',layout,margins=(0,0),finalize=True)
# ---- Convert im to ImageTk.PhotoImage after window finalized
image = ImageTk.PhotoImage(image=im)
# ---- update image in sg.Image
window['-IMAGE-'].update(data=image)
# ---- event loop
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
window.close()
argv and args
#!/usr/bin/python3
# ===================================================================
# comand line arguments
# ===================================================================
import sys
for arg in sys.argv:
print(arg)
#!/usr/bin/python3
# ===================================================================
# function arguments - using the unpacking operator (*) and (**)
# ===================================================================
def funcA(*args):
print(f'funcA *args is {type(args)}')
print(args)
def funcB(**kwargs):
print(f'funcA **kwargs is {type(kwargs)}')
print(kwargs)
def funcC(*args,**kwargs):
print(args)
print(kwargs)
funcA(1,2,3,4,'A','B','C','D')
print('---------------------------------')
funcB(a=1,b=2)
try:
funcB(99,98,a=1,b=2)
except Exception as e:
print(str(e))
funcC(99,98,a=1,b=2)
print("funcC(a=1,b=2,99,98")
print("SyntaxError: positional argument follows keyword argument")
print("funcC(99,a=1,98,b=1)")
print('SyntaxError: positional argument Follows keyword argument')
bytes and bytearray
#!/usr/bin/python3
# ===================================================================
# test/play with bytes and bytearray data types
# Note: data type bytes are immutable
# data type bytearray is mutable
# ===================================================================
print()
print('---- test bytes data type ------------------------------------')
a = [0,1,2,127,255,256]
print()
print(f'a = {a}')
try:
x = bytes(a)
print()
except Exception as e:
print(str(e))
print()
a = [0,1,2,127,255]
print(f'a = {a}')
try:
x = bytes(a)
print(f'x = {x}')
print('Try: x[0] = 45')
x[0] = 45
except Exception as e:
print(str(e))
print(f'x = {x}')
a = [0,1,2,127,255,ord('a')]
print()
print(f'a = {a} (ord value of character \'a\')')
try:
x = bytes(a)
print()
except Exception as e:
print(str(e))
print()
print('---- test bytearray data type --------------------------------')
a = [0,1,2,127,255,256]
print()
print(f'a = {a}')
try:
x = bytearray(a)
print()
except Exception as e:
print(str(e))
print()
a = [0,1,2,127,255]
print(f'a = {a}')
try:
x = bytearray(a)
print(f'x = {x}')
print('Try: x[0] = 45')
x[0] = 45
except Exception as e:
print(str(e))
print(f'x = {x}')
print()
print(f'(66 ord value of character \'B\')')
print(f'(97 ord value of character \'a\')')
a = [0,1,2,66,127,ord('a')]
for i in range(len(a)):
print(f'[{i}] {type(a[i])} {a[i]}')
try:
x = bytearray(a)
print()
except Exception as e:
print(str(e))
print(f'x = {x}')
print()
print(['a','b','c'])
print(f'(97 ord value of character \'a\')')
print(f'(98 ord value of character \'b\')')
print(f'(99 ord value of character \'c\')')
a = [ord('a'),ord('b'),ord('c')]
print(f'a = {a}')
x = bytearray(a)
for i in range(len(a)):
print(f'[{i}] {type(a[i])} {a[i]}')
try:
x = bytearray(a)
print()
except Exception as e:
print(str(e))
print(f'x = {x}')
Convert string to bytearray
a = bytearray(b'Mary had a little lamb.')
for x in a:
print(x, end=', ')
print()
print('---------------------------------------------')
print()
txt = 'Mary had a little lamb.'
a = bytearray(txt.encode('utf-8'))
for x in a:
print(x, end=', ')
print()
a = bytearray(b'Mary had \x263A a little lamb.')
print(a)
for x in a:
print(f'{x:x} ({chr(x)})', end=', ')
print()
print(f'len={len(a)}')
print()
print('---------------------------------------------')
print()
txt = 'Mary had \u263A a little lamb.'
print(txt)
a = bytearray(txt.encode('utf-8'))
for x in a.decode('utf-8'):
print(f'{ord(x):x} ({x})', end=', ')
print()
print(f'len={len(txt)}')
print()
Sort Using Multiple_Keys
#!/usr/bin/python3
# ===============================================================
# sort with multiple keys
# i.e sort by name within a zip code within a state
# ===============================================================
import sys
# --- test data - first name, state, zip code
data = [ ('first name 04', 'state 1', 900120),
('first name 01', 'state 1', 900122),
('first name 03', 'state 1', 900123),
('first name 02', 'state 1', 900121),
('first name 13', 'state 3', 700120),
('first name 12', 'state 3', 700121),
('first name 14', 'state 3', 700121),
('first name 11', 'state 9', 900120),
('first name 15', 'state 3', 700123),
('first name 16', 'state 3', 700121),
('first name 05', 'state 1', 900127),
('first name 06', 'state 2', 800121),
('first name 07', 'state 2', 800122),
('first name 08', 'state 2', 800123),
('first name 09', 'state 2', 800124),
('first name 10', 'state 3', 700126),
('first name 99', 'state 9', 100120)
]
# ---- sort by multiple keys (ascending order)
print()
print('sorted using multiple keys')
print()
print('sort name within zip within state')
print()
multi_sort = sorted(data, key=lambda x: (x[1],x[2],x[0]) )
for i,x in enumerate(multi_sort):
print(f'[{i:2}] {x[1]} {x[2]} {x[0]}')
Start/End Web Page
start_of_web_page = '''\
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="author" content="{author}" />
<link rel="stylesheet" href="{css1}" />
<link rel="stylesheet" href="{css2}" />
<link rel="icon" href="favicon.png" type="image/png" />
<link rel="shortcut icon" href="favicon.png" type="image/png" />
<title>{pagetitle}</title>
{style}
</head>
<body>
<header>
<center>{headertitle}</center>
</header>
<div class="indent12">
<p>'''
end_of_web_page = '''\
</p>
</div>
<footer>
<modate>Last Modified: {today}</modate>
</footer>
</body>
</html>'''
mystyle = '''\
<style>
modate { font-size: 0.8em; margin-left: 12px; }
</style>'''
import datetime as dt
def fstr(web_page,params):
return web_page.format(**params)
print()
x = fstr(start_of_web_page,
{'pagetitle' :'Page Title',
'author' :'George',
'css1' :'style1.css',
'css2' :'style2.css',
'style' :'mystyle',
'headertitle':'header Title'})
print(x)
print()
x = fstr(end_of_web_page,
{'today': dt.datetime.now().strftime("%B %d,%Y %H:%M:%S")})
print(x,end='')
List Comprehension
# ---- process a list of integers get a list of
# ---- every other integer
elements = [1,2,3,4,5,6,7,8,9,0,10,11,12,13,14,15,16,17]
l = [element for index,element in enumerate(elements) if index % 2 == 1]
print(l)
Random
from random import shuffle
names: list[str] = ['Tom', 'Judy', Jason',
'Barbara', 'Marie', 'Gretchen']
# ---- randomize a list (shuffle the list in place)
shuffle(names)
print(names)
from random import random, randint, randrange
# ---- random (random float in the range 0.0 <= X < 1.0)
value: float = random()
print(f'random() is {value}')
# ---- randint (random integer upper bound is included)
values: list[int] = [randint(10,20) for _ in range(5)]
print(randint() = {values})
# ---- randrange (random elements from range, upper bound is excluded)
values2: list[int] = [randrange(0,3) for _ in range(5)]
print(randrange() = {values2})
values3: list[int] = [randrange(0,10,2) for _ in range(5)]
print(randrange(with step = 2) = {values3})
from random import choice, choices
names: list[str] = ['Tom', 'Judy', Jason',
'Barbara', 'Marie', 'Gretchen']
# ---- select a random element from the list
print(f'choice() = {choice(names)')
# ---- select several random elements from the list
# ---- (the same element may be selected more that once)
print(f'choices() = {choices(names,k=3)}')
# ---- use selection weights (sum to 1.0)
# ---- (percentage probability a give element
# ---- will appear in the selected list)
weights: tuple = (.10, .20, .05, .25, .21, .29)
print(f'choices() = {choices(names,k=3,weights=weights)}')
from random import sample
# ---- the similar to choices except it will only
# ---- draw each element once from the list
# ---- every element in the list is considered unique
# ---- (e.g. [10, 10, 6, 7, 8] are all unique values)
print(samples(range(100),k=10)
# ---- something else we can do
colors: list[str] = ['r','g','b']
print(sample(colors,k=5,counts=(10,20,5)))
from random import seed
# ---- seed allows us to get consistent results back
# ---- (very important for testing)
seed(1491) # generate the same random values each time