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('')


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('')

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
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('')


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('')

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.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-replace-multiple-characters-at-once
Python - Replace multiple characters at once - GeeksforGeeks
July 12, 2025 - Replacing multiple characters in a string is a common task in Python Below, we explore methods to replace multiple characters at once, ranked from the most efficient to the least.
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?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. 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 - Learn how to replace multiple characters in string in python. This includes replace() with Lists, Dictionaries, re module and translate() & maketrans().
๐ŸŒ
Flexiple
flexiple.com โ€บ python โ€บ replace-multiple-char-python
Replacing Multiple Characters in Python - Flexiple
April 1, 2024 - The blog โ€˜Replacing Multiple Characters in Pythonโ€™ blog explains the various methods to replace multiple characters in Python.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ string-replace-method
Master Python's String Replace Method for Text Manipulation
You can also use replace() to replace single characters in a string rather than substrings. ... To replace multiple different characters in a string, you can chain multiple replace() calls or use the translate() method with a translation table.
๐ŸŒ
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
Find elsewhere
๐ŸŒ
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 - Define a function replace_multiple_chars_regex that takes an input string and a dictionary (replace_dict) specifying the characters to be replaced and their corresponding replacements.
๐ŸŒ
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 ...
๐ŸŒ
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.
๐ŸŒ
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
๐ŸŒ
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

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-replace-different-characters-in-string-at-once
Python - Replace Different Characters in String at Once - GeeksforGeeks
January 29, 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 replacements in one go.
๐ŸŒ
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....
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-replace-multiple-characters-at-once
Python - Replace multiple characters at once
October 3, 2023 - Let's explore multiple methods to solve this problem efficiently. This is the most straightforward method using Python's built-in replace function to replace desired characters ? string = "Total Tap if Tol on Treep is obvious" replace_dict = {"T": "S", "o": "w"} for old, new in replace_dict.items(): string = string.replace(old, new) print(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 - Best for single-character replacements. Fast and clean. text = "hello world!" replacements = {"h": "H", "w": "W", "!": "."} for old, new in replacements.items(): text = text.replace(old, new) print(text) After the replacement of the multiple chars at once:
๐ŸŒ
Pierian Training
pieriantraining.com โ€บ home โ€บ python tutorial: replace character in a string
Python Tutorial: Replace Character in a String - Pierian Training
April 27, 2023 - In conclusion, if you need to replace one or more characters in a string in Python, the replace() method provides an easy and efficient way to do so. In Python, we can replace multiple characters in a string using the `translate()` method.
๐ŸŒ
michael harty
mharty3.github.io โ€บ til โ€บ python โ€บ string-translate
Replace multiple characters in a string using string.translate() (python) - michael harty
October 30, 2023 - If you need to replace a character in a string, you can use string.replace(old, new) or re.swap(pattern, new, string) if you need regex.
๐ŸŒ
HCL GUVI
studytonight.com โ€บ python-howtos โ€บ how-to-replace-multiple-substrings-of-a-string-in-python
HCL GUVI | Learn to code in your native language
HCL GUVI's Data Science Program was just fantastic. It covered statistics, machine learning, data visualization, and Python within its curriculum.