Skip to content

Instantly share code, notes, and snippets.

@raeq
raeq / strings_10_execute.py
Created July 19, 2020 12:30
Execute code found in strings
import subprocess
import ast
def exec_string(input_string: str = "") -> str:
result = subprocess.getoutput(input_string)
return result
def eval_string(input_string: str = "") -> str:
@raeq
raeq / strings_12_punctuation.py
Created July 19, 2020 12:39
Remove punctuation from a string
import string
def remove_punctuation(input_string: str = "") -> str:
return input_string.translate(str.maketrans("", "", string.punctuation))
assert remove_punctuation("Hello!") == "Hello"
assert remove_punctuation("He. Saw! Me?") == "He Saw Me"
@raeq
raeq / strings_13_url.py
Created July 19, 2020 12:50
Encode and decode UTF-8 URL
import urllib.parse
def encode_url(url: str = "") -> str:
return urllib.parse.quote(url)
def decode_url(url: str = "") -> str:
return urllib.parse.unquote(url)
@raeq
raeq / strings_14_base64.py
Created July 19, 2020 13:03
Encode and Decode base64 strings
import base64
def encode_b64(input_string: str = "") -> object:
return base64.b64encode(input_string.encode("utf-8"))
def decode_b64(input_string: str = "") -> object:
return base64.b64decode(input_string).decode("utf-8")
@raeq
raeq / strings_14_tokenize.py
Created July 19, 2020 13:21
Tokenize a string using NLTK.
import nltk
def tokenize_text(input_str: str = "") -> list:
return nltk.wordpunct_tokenize(input_str)
assert tokenize_text("Good muffins cost $3.88\nin New York.") == [
"Good",
"muffins",
@raeq
raeq / strings_7_random.py
Created July 19, 2020 13:37
Generate random strings
import string
import secrets
def generate_random_string(length: int = 0) -> str:
result = "".join(
secrets.choice(string.ascii_letters + string.digits)
for _ in range(length))
return result
@raeq
raeq / strings_11_markers.py
Created July 19, 2020 13:53
Use REGEX to find text between two markers.
import re
def between(first: str = "", second: str = "", input_string="") -> str:
m = re.search(f"{first}(.+?){second}", input_string)
if m:
return m.group(1)
else:
@raeq
raeq / strings_22_char_class.py
Last active July 21, 2020 08:25
Check to See if a String Contains a Character Class
import string
def has_character_classes(input_string: str) -> tuple:
has_uppercase = False
has_lowercase = False
has_digits = False
has_whitespace = False
import requests
import json
def recursive_key_values(dictionary):
"""recursive_key_values.
Print all keys and values anywhere in a dictionary
Args:
dictionary: any dictionary
@raeq
raeq / dict_02_sort.py
Created July 30, 2020 15:56
Sorting a dictionary
"""
Sorting a dictionary to an Iterable of tuples.
https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_area
"""
countries: dict = {
"Taiwan": 36193,
"Canada": 9984670,
"United States": 9525067,
"Russia": 17098246,