Skip to content

Instantly share code, notes, and snippets.

import numpy as np
import matplotlib.pyplot as plt
import math
import array
import random
import pickle
import pandas as pd
from deap import base
from deap import benchmarks
from deap import creator
@carlsmith
carlsmith / replace.py
Created April 5, 2017 02:08
A Python function that does multiple string replace ops in a single pass.
import re
def replace(string, substitutions):
substrings = sorted(substitutions, key=len, reverse=True)
regex = re.compile('|'.join(map(re.escape, substrings)))
return regex.sub(lambda match: substitutions[match.group(0)], string)
@bgusach
bgusach / multireplace.py
Last active July 10, 2024 14:14
Python string multireplacement
def multireplace(string, replacements, ignore_case=False):
"""
Given a string and a replacement map, it returns the replaced string.
:param str string: string to execute replacements on
:param dict replacements: replacement dictionary {value to find: value to replace}
:param bool ignore_case: whether the match should be case insensitive
:rtype: str
"""