Skip to content

Instantly share code, notes, and snippets.

@MeryllEssig
Created January 14, 2017 13:42
Show Gist options
  • Save MeryllEssig/bb879b38e48d070f94af684964605d37 to your computer and use it in GitHub Desktop.
Save MeryllEssig/bb879b38e48d070f94af684964605d37 to your computer and use it in GitHub Desktop.
python snippets
food = ["pizza", "tacos", "ice cream", "cupcakes", "burgers"]
print(', '.join(str(x) for x in food))
print(*food, sep=", ")
#output: pizza, tacos, ice cream, cupcakes, burgers
p = backwards
print p[::-1]
#output: sdrawkcab
name = "Jon"
age = 28
fave_food = "burritos"
fave_color = "green"
string = "Hey, I'm {0} and I'm {1} years old. I love {2} and my favorite color is {3}.".format(name,
age, fave_food, fave_color)
print(string)
#output: Hey, I'm Jon and I'm 28 years old. I love burritos and my favorite color is green.
x = array([3, 6, 9, 12])
x/3.0
print(x)
#output: array([1, 2, 3, 4])
y = [3, 6, 9, 12]
y/3.0
print(y)
#output: exception -> arrays are more straightforward than lists for arithmetic operations.
age = 15
# Conditions are evaluated from left to right
print('kid' if age < 18 else 'adult')
#output: kid
print(('adult', 'kid')[age < 20])
#output: kid
print({True: 'kid', False: 'adult'}[age < 20])
#output: kid
import random
items = ['here', 'are', 'some', 'strings', 'of',
'which', 'we', 'will', 'select', 'one']
rand_item = items[random.randrange(len(items))] #one item
rand_items = [items[random.randrange(len(items))] #multiple items
for item in range(4)]
rand_item = random.choice(items) #easier
rand_items = random.sample(items, n) #multiple items
os.access('foo.txt', os.R_OK)
True # This means the file exists AND you can read it.
os.access('foo.txt', os.W_OK)
False # You cannot write to the file. It may or may not exist.
try:
f = open('foo.txt')
f.close()
except IOError as e:
print('Uh oh!')
def file_accessible(filepath, mode):
''' Check if a file exists and is accessible. '''
try:
f = open(filepath, mode)
f.close()
except IOError as e:
return False
return True
def lessThan(cutoffVal, *vals) :
''' Return a list of values less than the cutoff. '''
arr = []
for val in vals :
if val < cutoffVal:
arr.append(val)
return arr
print(lessThan(10, 2, 17, -3, 42))
#output: [2, -3]
def printVals(prefix='', **dict):
# Print out the extra named parameters and their values
for key, val in dict.items():
print('%s [%s] => [%s]' % (prefix, str(key), str(val)))
def formatString(stringTemplate, *args, **kwargs):
# Replace any positional parameters
for i in range(0, len(args)):
tmp = '{%s}' % str(1+i)
while True:
pos = stringTemplate.find(tmp)
if pos < 0:
break
stringTemplate = stringTemplate[:pos] + \
str(args[i]) + \
stringTemplate[pos+len(tmp):]
# Replace any named parameters
for key, val in kwargs.items():
tmp = '{%s}' % key
while True:
pos = stringTemplate.find(tmp)
if pos < 0:
break
stringTemplate = stringTemplate[:pos] + \
str(val) + \
stringTemplate[pos+len(tmp):]
return stringTemplate
#real example
stringTemplate = 'pos1={1} pos2={2} pos3={3} foo={foo} bar={bar}'
print(formatString(stringTemplate, 1, 2))
#output: pos1=1 pos2=2 pos3={3} foo={foo} bar={bar}
print(formatString(stringTemplate, 42, bar=123, foo='hello'))
#output: pos1=42 pos2={2} pos3={3} foo=hello bar=123
import re
def isValidEmail(email):
if len(email) > 7:
if re.match("^.+@([?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$", email) != None:
return True
return False
if isValidEmail("[email protected]") == True :
print "This is a valid email address"
else:
print "This is not a valid email address"
import time
## 24 hour format ##
print (time.strftime("%H:%M:%S"))
## 12 hour format ##
print (time.strftime("%I:%M:%S"))
## dd/mm/yyyy format
print (time.strftime("%d/%m/%Y"))
## mm/dd/yyyy format
print (time.strftime("%m/%d/%Y"))
## dd/mm/yyyy hh:mm:ss format
print (time.strftime('%d/%m/%Y %H:%M:%S'))
## mm/dd/yyyy hh:mm:ss format
print (time.strftime('%m/%d/%Y %H:%M:%S'))
a = "Learning Python is super fun!"
"super" in a
##output: True
import sys
x=1500
sys.setrecursionlimit(x) # Defaults at 1000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment