Index

basic types

strings

trim / strip
line.strip()
string is empty
line.strip() == ""
length of string
len(line)
string starts with
line.startswith("http")
substring
line[3:len(line)]
splitting a string on a literal separator of one or more characters
variable.split('.')
universal to string method
str(object)

numbers

convert to int
int(float('14.3'))
int('15')

arrays

stack = []
stack.append('value')
for value in stack:
    print(value)
array length
len(stack)

regex

import re
result = re.search('.+/([^/]+)\\.git\\s*', line, re.IGNORECASE)
if result:
repo = result.group(1)

input / output

print without newline
print(line, end="")
command line arguments
import sys
count = len(sys.argv)
first = sys.argv[1]
for arg in sys.argv:
    print arg
piped input
echo -e "a\nb" | python -c '
import sys
for line in sys.stdin:
    sys.stdout.write(line)
'
write file
file = open('workfile', 'w')
file.write('This is a test\n')
read file
file = open('workfile', 'r')
file.read()
read lines
file = open('workfile', 'r')
for line in file:
    print(line, end='')
verify directory
import os.path
if not os.path.isfile('work'):
if not os.path.isdir('work'):
create directory
import os
os.mkdir('work')
get home directory
os.getenv("HOME")
calling a shell process
import subprocess
subprocess.Popen(['/path/to/script.sh'])
calling a shell process and passing in environment variables
import os
import subprocess
variables=dict(os.environ, APPLE='PEAR')
subprocess.Popen(['/usr/bin/env'], env=variables)
ternary operator
result = [if_value] if [condition] else [else_value]
for loop with fixed iterations
for i in range(10):
	print(i)

exception handling

throw an exception
raise Exception('This user appears unequipped to use this application!')

threads

sleep
import time
time.sleep(10)

one liners

call python with script as argument
python -c 'print("hello world")'
use piped input
echo "hello world" | python -c "import sys; print(sys.stdin.read())"
use piped input line for line
echo -e "a b\r\nc d" | python3 -c 'import sys; [print(line, end="") for line in sys.stdin]'