Replacing two characters

I timed all the methods in the current answers along with one extra.

With an input string of abc&def#ghi and replacing & -> \& and # -> \#, the fastest way was to chain together the replacements like this: text.replace('&', '\&').replace('#', '\#').

Timings for each function:

  • a) 1000000 loops, best of 3: 1.47 ฮผs per loop
  • b) 1000000 loops, best of 3: 1.51 ฮผs per loop
  • c) 100000 loops, best of 3: 12.3 ฮผs per loop
  • d) 100000 loops, best of 3: 12 ฮผs per loop
  • e) 100000 loops, best of 3: 3.27 ฮผs per loop
  • f) 1000000 loops, best of 3: 0.817 ฮผs per loop
  • g) 100000 loops, best of 3: 3.64 ฮผs per loop
  • h) 1000000 loops, best of 3: 0.927 ฮผs per loop
  • i) 1000000 loops, best of 3: 0.814 ฮผs per loop

Here are the functions:

def a(text):
    chars = "&#"
    for c in chars:
        text = text.replace(c, "\\" + c)


def b(text):
    for ch in ['&','#']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)


import re
def c(text):
    rx = re.compile('([&#])')
    text = rx.sub(r'\\\1', text)


RX = re.compile('([&#])')
def d(text):
    text = RX.sub(r'\\\1', text)


def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('&#')
def e(text):
    esc(text)


def f(text):
    text = text.replace('&', '\&').replace('#', '\#')


def g(text):
    replacements = {"&": "\&", "#": "\#"}
    text = "".join([replacements.get(c, c) for c in text])


def h(text):
    text = text.replace('&', r'\&')
    text = text.replace('#', r'\#')


def i(text):
    text = text.replace('&', r'\&').replace('#', r'\#')

Timed like this:

python -mtimeit -s"import time_functions" "time_functions.a('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.b('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.c('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.d('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.e('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.f('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.g('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.h('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.i('abc&def#ghi')"

Replacing 17 characters

Here's similar code to do the same but with more characters to escape (\`*_{}>#+-.!$):

def a(text):
    chars = "\\`*_{}>#+-.!$"
    for c in chars:
        text = text.replace(c, "\\" + c)


def b(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)


import re
def c(text):
    rx = re.compile('([&#])')
    text = rx.sub(r'\\\1', text)


RX = re.compile('(\\`*_{}[>#+-.!$])')
def d(text):
    text = RX.sub(r'\\\1', text)


def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('\\`*_{}>#+-.!$')
def e(text):
    esc(text)


def f(text):
    text = text.replace('\\', '\\\\').replace('`', '\`').replace('*', '\*').replace('_', '\_').replace('{', '\{').replace('}', '\}').replace('[', '\[').replace(']', '\]').replace('(', '\(').replace(')', '\)').replace('>', '\>').replace('#', '\#').replace('+', '\+').replace('-', '\-').replace('.', '\.').replace('!', '\!').replace('$', '\$')


def g(text):
    replacements = {
        "\\": "\\\\",
        "`": "\`",
        "*": "\*",
        "_": "\_",
        "{": "\{",
        "}": "\}",
        "[": "\[",
        "]": "\]",
        "(": "\(",
        ")": "\)",
        ">": "\>",
        "#": "\#",
        "+": "\+",
        "-": "\-",
        ".": "\.",
        "!": "\!",
        "$": "\$",
    }
    text = "".join([replacements.get(c, c) for c in text])


def h(text):
    text = text.replace('\\', r'\\')
    text = text.replace('`', r'\`')
    text = text.replace('*', r'\*')
    text = text.replace('_', r'\_')
    text = text.replace('{', r'\{')
    text = text.replace('}', r'\}')
    text = text.replace('[', r'\[')
    text = text.replace(']', r'\]')
    text = text.replace('(', r'\(')
    text = text.replace(')', r'\)')
    text = text.replace('>', r'\>')
    text = text.replace('#', r'\#')
    text = text.replace('+', r'\+')
    text = text.replace('-', r'\-')
    text = text.replace('.', r'\.')
    text = text.replace('!', r'\!')
    text = text.replace('$', r'\$')


def i(text):
    text = text.replace('\\', r'\\').replace('`', r'\`').replace('*', r'\*').replace('_', r'\_').replace('{', r'\{').replace('}', r'\}').replace('[', r'\[').replace(']', r'\]').replace('(', r'\(').replace(')', r'\)').replace('>', r'\>').replace('#', r'\#').replace('+', r'\+').replace('-', r'\-').replace('.', r'\.').replace('!', r'\!').replace('$', r'\$')

Here's the results for the same input string abc&def#ghi:

  • a) 100000 loops, best of 3: 6.72 ฮผs per loop
  • b) 100000 loops, best of 3: 2.64 ฮผs per loop
  • c) 100000 loops, best of 3: 11.9 ฮผs per loop
  • d) 100000 loops, best of 3: 4.92 ฮผs per loop
  • e) 100000 loops, best of 3: 2.96 ฮผs per loop
  • f) 100000 loops, best of 3: 4.29 ฮผs per loop
  • g) 100000 loops, best of 3: 4.68 ฮผs per loop
  • h) 100000 loops, best of 3: 4.73 ฮผs per loop
  • i) 100000 loops, best of 3: 4.24 ฮผs per loop

And with a longer input string (## *Something* and [another] thing in a longer sentence with {more} things to replace$):

  • a) 100000 loops, best of 3: 7.59 ฮผs per loop
  • b) 100000 loops, best of 3: 6.54 ฮผs per loop
  • c) 100000 loops, best of 3: 16.9 ฮผs per loop
  • d) 100000 loops, best of 3: 7.29 ฮผs per loop
  • e) 100000 loops, best of 3: 12.2 ฮผs per loop
  • f) 100000 loops, best of 3: 5.38 ฮผs per loop
  • g) 10000 loops, best of 3: 21.7 ฮผs per loop
  • h) 100000 loops, best of 3: 5.7 ฮผs per loop
  • i) 100000 loops, best of 3: 5.13 ฮผs per loop

Adding a couple of variants:

def ab(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        text = text.replace(ch,"\\"+ch)


def ba(text):
    chars = "\\`*_{}>#+-.!$"
    for c in chars:
        if c in text:
            text = text.replace(c, "\\" + c)

With the shorter input:

  • ab) 100000 loops, best of 3: 7.05 ฮผs per loop
  • ba) 100000 loops, best of 3: 2.4 ฮผs per loop

With the longer input:

  • ab) 100000 loops, best of 3: 7.71 ฮผs per loop
  • ba) 100000 loops, best of 3: 6.08 ฮผs per loop

So I'm going to use ba for readability and speed.

Addendum

Prompted by haccks in the comments, one difference between ab and ba is the if c in text: check. Let's test them against two more variants:

def ab_with_check(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)

def ba_without_check(text):
    chars = "\\`*_{}>#+-.!$"
    for c in chars:
        text = text.replace(c, "\\" + c)

Times in ฮผs per loop on Python 2.7.14 and 3.6.3, and on a different machine from the earlier set, so cannot be compared directly.

โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฅโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ Py, input  โ•‘  ab  โ”‚ ab_with_check โ”‚  ba  โ”‚ ba_without_check โ”‚
โ•žโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฌโ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ก
โ”‚ Py2, short โ•‘ 8.81 โ”‚    4.22       โ”‚ 3.45 โ”‚    8.01          โ”‚
โ”‚ Py3, short โ•‘ 5.54 โ”‚    1.34       โ”‚ 1.46 โ”‚    5.34          โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ซโ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Py2, long  โ•‘ 9.3  โ”‚    7.15       โ”‚ 6.85 โ”‚    8.55          โ”‚
โ”‚ Py3, long  โ•‘ 7.43 โ”‚    4.38       โ”‚ 4.41 โ”‚    7.02          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•จโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

We can conclude that:

  • Those with the check are up to 4x faster than those without the check

  • ab_with_check is slightly in the lead on Python 3, but ba (with check) has a greater lead on Python 2

  • However, the biggest lesson here is Python 3 is up to 3x faster than Python 2! There's not a huge difference between the slowest on Python 3 and fastest on Python 2!

Answer from Hugo on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-replace-multiple-characters-at-once
Python - Replace multiple characters at once - GeeksforGeeks
July 12, 2025 - ... s = "hello world" replacements = {"h": "H", "e": "E", "o": "O"} for old, new in replacements.items(): s = s.replace(old, new) print(s) The replace() method handles one replacement at a time.
Top answer
1 of 16
765

Replacing two characters

I timed all the methods in the current answers along with one extra.

With an input string of abc&def#ghi and replacing & -> \& and # -> \#, the fastest way was to chain together the replacements like this: text.replace('&', '\&').replace('#', '\#').

Timings for each function:

  • a) 1000000 loops, best of 3: 1.47 ฮผs per loop
  • b) 1000000 loops, best of 3: 1.51 ฮผs per loop
  • c) 100000 loops, best of 3: 12.3 ฮผs per loop
  • d) 100000 loops, best of 3: 12 ฮผs per loop
  • e) 100000 loops, best of 3: 3.27 ฮผs per loop
  • f) 1000000 loops, best of 3: 0.817 ฮผs per loop
  • g) 100000 loops, best of 3: 3.64 ฮผs per loop
  • h) 1000000 loops, best of 3: 0.927 ฮผs per loop
  • i) 1000000 loops, best of 3: 0.814 ฮผs per loop

Here are the functions:

def a(text):
    chars = "&#"
    for c in chars:
        text = text.replace(c, "\\" + c)


def b(text):
    for ch in ['&','#']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)


import re
def c(text):
    rx = re.compile('([&#])')
    text = rx.sub(r'\\\1', text)


RX = re.compile('([&#])')
def d(text):
    text = RX.sub(r'\\\1', text)


def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('&#')
def e(text):
    esc(text)


def f(text):
    text = text.replace('&', '\&').replace('#', '\#')


def g(text):
    replacements = {"&": "\&", "#": "\#"}
    text = "".join([replacements.get(c, c) for c in text])


def h(text):
    text = text.replace('&', r'\&')
    text = text.replace('#', r'\#')


def i(text):
    text = text.replace('&', r'\&').replace('#', r'\#')

Timed like this:

python -mtimeit -s"import time_functions" "time_functions.a('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.b('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.c('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.d('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.e('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.f('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.g('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.h('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.i('abc&def#ghi')"

Replacing 17 characters

Here's similar code to do the same but with more characters to escape (\`*_{}>#+-.!$):

def a(text):
    chars = "\\`*_{}>#+-.!$"
    for c in chars:
        text = text.replace(c, "\\" + c)


def b(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)


import re
def c(text):
    rx = re.compile('([&#])')
    text = rx.sub(r'\\\1', text)


RX = re.compile('(\\`*_{}[>#+-.!$])')
def d(text):
    text = RX.sub(r'\\\1', text)


def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('\\`*_{}>#+-.!$')
def e(text):
    esc(text)


def f(text):
    text = text.replace('\\', '\\\\').replace('`', '\`').replace('*', '\*').replace('_', '\_').replace('{', '\{').replace('}', '\}').replace('[', '\[').replace(']', '\]').replace('(', '\(').replace(')', '\)').replace('>', '\>').replace('#', '\#').replace('+', '\+').replace('-', '\-').replace('.', '\.').replace('!', '\!').replace('$', '\$')


def g(text):
    replacements = {
        "\\": "\\\\",
        "`": "\`",
        "*": "\*",
        "_": "\_",
        "{": "\{",
        "}": "\}",
        "[": "\[",
        "]": "\]",
        "(": "\(",
        ")": "\)",
        ">": "\>",
        "#": "\#",
        "+": "\+",
        "-": "\-",
        ".": "\.",
        "!": "\!",
        "$": "\$",
    }
    text = "".join([replacements.get(c, c) for c in text])


def h(text):
    text = text.replace('\\', r'\\')
    text = text.replace('`', r'\`')
    text = text.replace('*', r'\*')
    text = text.replace('_', r'\_')
    text = text.replace('{', r'\{')
    text = text.replace('}', r'\}')
    text = text.replace('[', r'\[')
    text = text.replace(']', r'\]')
    text = text.replace('(', r'\(')
    text = text.replace(')', r'\)')
    text = text.replace('>', r'\>')
    text = text.replace('#', r'\#')
    text = text.replace('+', r'\+')
    text = text.replace('-', r'\-')
    text = text.replace('.', r'\.')
    text = text.replace('!', r'\!')
    text = text.replace('$', r'\$')


def i(text):
    text = text.replace('\\', r'\\').replace('`', r'\`').replace('*', r'\*').replace('_', r'\_').replace('{', r'\{').replace('}', r'\}').replace('[', r'\[').replace(']', r'\]').replace('(', r'\(').replace(')', r'\)').replace('>', r'\>').replace('#', r'\#').replace('+', r'\+').replace('-', r'\-').replace('.', r'\.').replace('!', r'\!').replace('$', r'\$')

Here's the results for the same input string abc&def#ghi:

  • a) 100000 loops, best of 3: 6.72 ฮผs per loop
  • b) 100000 loops, best of 3: 2.64 ฮผs per loop
  • c) 100000 loops, best of 3: 11.9 ฮผs per loop
  • d) 100000 loops, best of 3: 4.92 ฮผs per loop
  • e) 100000 loops, best of 3: 2.96 ฮผs per loop
  • f) 100000 loops, best of 3: 4.29 ฮผs per loop
  • g) 100000 loops, best of 3: 4.68 ฮผs per loop
  • h) 100000 loops, best of 3: 4.73 ฮผs per loop
  • i) 100000 loops, best of 3: 4.24 ฮผs per loop

And with a longer input string (## *Something* and [another] thing in a longer sentence with {more} things to replace$):

  • a) 100000 loops, best of 3: 7.59 ฮผs per loop
  • b) 100000 loops, best of 3: 6.54 ฮผs per loop
  • c) 100000 loops, best of 3: 16.9 ฮผs per loop
  • d) 100000 loops, best of 3: 7.29 ฮผs per loop
  • e) 100000 loops, best of 3: 12.2 ฮผs per loop
  • f) 100000 loops, best of 3: 5.38 ฮผs per loop
  • g) 10000 loops, best of 3: 21.7 ฮผs per loop
  • h) 100000 loops, best of 3: 5.7 ฮผs per loop
  • i) 100000 loops, best of 3: 5.13 ฮผs per loop

Adding a couple of variants:

def ab(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        text = text.replace(ch,"\\"+ch)


def ba(text):
    chars = "\\`*_{}>#+-.!$"
    for c in chars:
        if c in text:
            text = text.replace(c, "\\" + c)

With the shorter input:

  • ab) 100000 loops, best of 3: 7.05 ฮผs per loop
  • ba) 100000 loops, best of 3: 2.4 ฮผs per loop

With the longer input:

  • ab) 100000 loops, best of 3: 7.71 ฮผs per loop
  • ba) 100000 loops, best of 3: 6.08 ฮผs per loop

So I'm going to use ba for readability and speed.

Addendum

Prompted by haccks in the comments, one difference between ab and ba is the if c in text: check. Let's test them against two more variants:

def ab_with_check(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)

def ba_without_check(text):
    chars = "\\`*_{}>#+-.!$"
    for c in chars:
        text = text.replace(c, "\\" + c)

Times in ฮผs per loop on Python 2.7.14 and 3.6.3, and on a different machine from the earlier set, so cannot be compared directly.

โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฅโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ Py, input  โ•‘  ab  โ”‚ ab_with_check โ”‚  ba  โ”‚ ba_without_check โ”‚
โ•žโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฌโ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ก
โ”‚ Py2, short โ•‘ 8.81 โ”‚    4.22       โ”‚ 3.45 โ”‚    8.01          โ”‚
โ”‚ Py3, short โ•‘ 5.54 โ”‚    1.34       โ”‚ 1.46 โ”‚    5.34          โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ซโ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Py2, long  โ•‘ 9.3  โ”‚    7.15       โ”‚ 6.85 โ”‚    8.55          โ”‚
โ”‚ Py3, long  โ•‘ 7.43 โ”‚    4.38       โ”‚ 4.41 โ”‚    7.02          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•จโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

We can conclude that:

  • Those with the check are up to 4x faster than those without the check

  • ab_with_check is slightly in the lead on Python 3, but ba (with check) has a greater lead on Python 2

  • However, the biggest lesson here is Python 3 is up to 3x faster than Python 2! There's not a huge difference between the slowest on Python 3 and fastest on Python 2!

2 of 16
97

Here is a python3 method using str.translate and str.maketrans:

s = "abc&def#ghi"
print(s.translate(str.maketrans({'&': '\&', '#': '\#'})))

The printed string is abc\&def\#ghi.

Discussions

Is there an easier way to replace multiple different things at once
On a high level, the method youโ€™ve demonstrated is both idiomatic and the fastest (or one at least one of them). However, a bit of reorganization will make it both a little more efficient (by not leaving the file handle open as long), and will ensure it looks cleaner and more readable. More on discuss.python.org
๐ŸŒ discuss.python.org
4
1
March 14, 2022
how to replace multiple characters in one go with the .replace() function?
re.sub, maketrans, or a list comprehension with join newstr = ''.join('*' if c in 'aA' else c for c in oldstr) More on reddit.com
๐ŸŒ r/learnpython
5
1
October 7, 2020
Which is the better way to include multiple '.replace()' ?
For this case, why not just timestamp = time.strftime("%Y%m%d_%H%M%S", t_obj) More on reddit.com
๐ŸŒ r/learnpython
6
3
January 1, 2023
Python: How can I replace one specific character on a string while leaving the rest of the string as it was?
str.replace replaces all instances of the search string with the replacement string, which isn't what you want the correct solution would be to turn the string into a list, update the value at the wanted index and then "".join(char_list) to rebuild the string More on reddit.com
๐ŸŒ r/learnprogramming
12
6
October 18, 2023
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ replace-multiple-characters-in-string-python
5 Ways to Replace Multiple Characters in String in Python
October 10, 2022 - After initializing the list, you can either replace the mentioned characters with the same character (i.e. all by one) or with multiple characters (i.e. a different character for each). Case: Replacing multiple characters with the same character: # multiple characters to be replace string = "FavTutor Blog: How to Remove multiple characters in a string in Python" # let's say we need to replace characters - 't', 'l', 'r' # creating a list for the characters to be replaced char_remov = ["t", "l", "r"] print("Original string: " + string) # let's say we need to replace them with a special character '#' # Using the for loop for each character of char_remov for char in char_remov: # replace() "returns" an altered string string = string.replace(char, "#") print("Altered string: " + string)
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-replace-different-characters-in-string-at-once
Python - Replace Different Characters in String at Once - GeeksforGeeks
July 15, 2025 - This method uses re.sub() function from Python's re module to replace characters in a string. It allows us to define a pattern to match characters and replace them efficiently. This is a flexible approach, especially when working with multiple ...
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python replace multiple characters
How to Replace Multiple Characters in a String in Python | Delft Stack
February 2, 2024 - Finally, we introduced the combination of str.maketrans and str.translate as a powerful duo for multiple character replacements. The str.maketrans method efficiently generates a translation table, and str.translate applies this table to replace characters in the string. Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe ... Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Is there an easier way to replace multiple different things at once - Python Help - Discussions on Python.org
March 14, 2022 - im trying to use the .replace() mutiple times at once and i was wondering if there was a cleaner way to do it Code example: with open("user_data.txt", "w") as f: f.write(str(user_data).replace("{","{\n").replace("}","\n}").replace(",",",\n")) f.close() the code works fine but looks a bit messy
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ python-replace-multiple-characters-in-string
How to replace multiple Characters in a String in Python | bobbyhadz
If the condition is met, we replace the substring with the replacement string and reassign the variable. You can also use the re.sub() method to replace multiple characters in a string with a single character.
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to replace multiple characters in one go with the .replace() function?
r/learnpython on Reddit: how to replace multiple characters in one go with the .replace() function?
October 7, 2020 -

Hello, I would like to replace a certain letter in a string with a '*' (don't ask lol)

The problem is it will only either do it for the lower case letters or upper case letters.

Is there a way to get the function to replace both upper and lower case letters or am I going to need to use the function twice?

Thanks

๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Replace Strings in Python: replace(), translate(), and Regex | note.nkmk.me
May 4, 2025 - Use square brackets ([]) to create a pattern matching any character within the brackets. This pattern allows you to replace multiple characters with the same string.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-replace-multiple-occurrence-of-character-by-single
Python | Replace multiple occurrence of character by single - GeeksforGeeks
July 31, 2023 - If repeated multiple times, append the character single time to the list. Other characters(Not the given character) are simply appended to the list without any alteration. ... # Python program to replace multiple # occurrences of a character ...
๐ŸŒ
Pierian Training
pieriantraining.com โ€บ home โ€บ python tutorial: replace character in a string
Python Tutorial: Replace Character in a String - Pierian Training
April 27, 2023 - To create a string variable in Python, simply assign it to a value enclosed in either single or double quotation marks: ... Python provides many built-in functions for working with strings. One of these functions is the `replace()` function, which ...
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ python replace multiple characters in string | example code
Python replace multiple characters in string | Example code - EyeHunts
August 4, 2021 - A for-loop needed to iterate over a list of characters to replace. Replacing the list of char with โ€œZโ€œ. a_string = "Hello world" replace_char = ["e", "w"] for char in replace_char: a_string = a_string.replace(char, "Z") print(a_string) ... Works only in Python2. import string test_str = "aaa bb cc" res = test_str.translate(string.maketrans("a", "b")) print(res) Replace vowels with space, where a string is given by the user.
๐ŸŒ
Codingzap
codingzap.com โ€บ home โ€บ blog โ€“ programming & coding articles โ€บ how to replace multiple characters in string in python?
How To Replace Multiple Characters In String In Python?
February 24, 2026 - Whatever the original string is, ... multiple occurrences of characters in a string is by using the sub() function from the built-in Regular Expressions (re) module....
๐ŸŒ
Replit
replit.com โ€บ discover โ€บ how-to-replace-multiple-characters-in-a-string-in-python
Discover | Replit
Describe what you want. Replit builds it. Get a working app or website in minutes. No coding required.
๐ŸŒ
CodeVsColor
codevscolor.com โ€บ python program to replace single or multiple character,substring in a string - codevscolor
Python program to replace single or multiple character,substring in a string - CodeVsColor
September 17, 2018 - We can also use the same method to replace one substring in a string like below : Similar to the above examples, we can also pass the value of count to replace a character or substring for count number of times in a string. Letโ€™s take a look : As you can see above that only two Hello was replaced instead of all if we are passing the value of count as 2. You can try the same example with a single character instead of a substring. Python doesnโ€™t provide any method to replace multiple different characters or substring in a string.
๐ŸŒ
Softhints
softhints.com โ€บ how-to-replace-multiple-characters-in-a-string-in-python
How to Replace Multiple Characters in a String in Python
April 12, 2025 - Works for replacing multiple characters or substrings. ... Flexible, readable. ... import re text = "hello world!" replacements = {"h": "H", "w": "W", "!": "."} pattern = re.compile("|".join(map(re.escape, replacements))) result = pattern.sub(lambda m: replacements[m.group(0)], text) print(result) ... Ideal for complex replacements or overlapping patterns. ... By using SoftHints - Python, Linux, Pandas , you agree to our Cookie Policy.
๐ŸŒ
YouTube
youtube.com โ€บ python basics
Python Basics Tutorial How to Replace Multiple String Characters || String Replace - YouTube
Learn how to replace more than one character at a time with python programmingPatreon:https://www.patreon.com/Python_basicsGithub:https://github.com/Python-b
Published: November 30, 2020
Views: 19K
๐ŸŒ
Its Linux FOSS
itslinuxfoss.com โ€บ home โ€บ python โ€บ how to replace multiple characters in a string in python?
How to Replace Multiple Characters in a String in Python? โ€“ Its Linux FOSS
January 29, 2023 - To replace multiple characters, various functions are used in Python. ... In Python, the โ€œreplace()โ€ function replaces occurrences of the substrings in a string with another substring.
๐ŸŒ
Quora
quora.com โ€บ In-Python-how-do-I-use-the-replace-function-on-strings-to-replace-multiple-characters-e-g-a-space-or-any-special-character-with-the-empty-string-E-g-Tes-ting-replace-only-replaces-the-space-not-the
In Python, how do I use the .replace() function on strings to replace multiple characters, e.g. a space or any special character, with th...
Answer (1 of 4): Why do you ask how to use a function (method) to do something after youโ€™ve already demonstrated to yourself that the function/method doesnโ€™t do that? Perhaps itโ€™s better to describe what you want to accomplish and ask which functions or methods might already exist to ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ python-replace-multiple-characters-at-once
Python - Replace multiple characters at once
March 27, 2026 - import re string_text = "Total Tap if Tol on Treep is obvious" replace_dict = {"T": "S", "o": "w"} pattern = re.compile("|".join(map(re.escape, replace_dict.keys()))) result = pattern.sub(lambda match: replace_dict[match.group(0)], string_text) print(result) ... We create a regex pattern by joining dictionary keys with the OR operator (|). The re.sub() function finds matches and replaces them using a lambda function that looks up replacement values in the dictionary. This method combines list comprehension with the join() method for character-by-character replacement ?