HaskellPlease
HaskellPlease

Reputation: 277

Python - replace letters in a string only once

I need to figure out how I can replace letters in python only once.

example:

s = "a b c d b"

# change letter 'a' to "bye" and letter 'b' to "hay"
# .replace function is problematic because:

s = s.replace('a', "bye")
print(s)

# will print to "bye b c d b" now if I try to replace letter b 
# it will replace the first b of "bye" aswell thats not what I want
# output I want: "bye hay c d hay"

Any help is appreciated

Upvotes: 1

Views: 717

Answers (3)

CrazyChucky
CrazyChucky

Reputation: 3518

I like Dani Mesejo's suggestion of using re.sub, but I find it easier to use when wrapped in a convenient function like so:

import re

def multi_replace(text, changes):
    return re.sub(
        '|'.join(changes),
        lambda match: changes[match.group()],
        text
    )
    
text = 'a b c d b'
changes = {'a': 'bye', 'b': 'hay'}

text = multi_replace(text, changes)
print(text)

Output:

bye hay c d hay

You can simply call multi_replace() with any text and dictionary of changes as input, even ones generated dynamically, and it will happily return the updated text.

Upvotes: -1

Collin Heist
Collin Heist

Reputation: 2682

If you know of a character that is not present in your original string, the easiest way (requiring no additional packages) would be to replace all characters to those 'temp' characters, and then replace those temp characters. For example:

s = 'a b c d b'

s = s.replace('a', '\0').replace('b', '\1') # Put temporary characters
s = s.replace('\0', 'bye').replace('\1', 'hay') # Replace temporary characters

Upvotes: 1

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could use a re.sub, as follows:

import re

s = "a b c d b"


def repl(e, lookup={"a": "bye", "b": "hay"}):
    return lookup.get(e.group(), e.group)


result = re.sub("[ab]", repl, s)
print(result)

Output

bye hay c d hay

Quoting the documentation of sub:

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function

Upvotes: 5

Related Questions