Skip to content

Instantly share code, notes, and snippets.

# Remove either all or selected punctuation marks from a string
import string
s = "John's in-depth response: \"It's mind-blowing!\""
t1 = str.maketrans('', '', string.punctuation)
t2 = str.maketrans('', '', ',.?!:;…')
r1 = s.translate(t1)
import re
from collections import Counter
text = 'I felt happy because I saw the others were happy and because I knew I should feel happy, but I wasn’t really happy.'
words = re.findall(r'\w+', text.lower())
counted_words = Counter(words)
for w in counted_words.most_common(3):
print(w)
# case one: make a munged password from a word by substituting
# regular letters with look-alike chars
word = 'jellyfish'
char_map = {'a': '@', 'c': '(', 'e': '3', 'l': '1', 'o': '0', 's': '5'}
sub_table = str.maketrans(char_map)
password = word.translate(sub_table)
assert password == 'j311yfi5h'
@tvey
tvey / dict_union.py
Last active September 3, 2021 06:42
Join Python dicts
produce = {'apples, pcs': 6, 'potatoes, kg': 2, 'tomatoes, pcs': 4}
dairy = {'cheese, g': 300, 'milk, packs': 1, 'yogurt, pcs': 4}
grains = {'oats, packs': 2, 'rice, packs': 1}
# can merge as many dicts as needed
shopping_list = produce | dairy | grains
# augmented assignment updates an existing dict in-place
shopping_list |= {'ice cream, pcs': 1}