« Back to Index

[Python Multiple Characters String Replacement]

View original Gist on GitHub

Tags: #python #replacement #string #translate

string replacement.py

"^foo$".translate(str.maketrans({'^': '', '$': ''}))

# more structured than...
"^foo$".replace("^", "").replace("$", "")

# and likely easier abstraction than using a regex replacement
#
# although you can do this more 'manually' like so...

def replace_all(text, dic):
    for i, j in dic.items():
        text = text.replace(i, j)
    return text

d = { "\n": "", "\r": ""}
my_sentence = "This is my cat\n\rand this\nis\rmy dog."
replace_all(my_sentence, d)  # 'This is my catand thisismy dog.'