简体   繁体   中英

Replacing a character in a stringin Python

I would like to replace a character in a string like so, WITHOUT using the string function or anything like string.replace.

 >>> replace ("banana", "a", "e")
'benene'

So for the example, I want to replace character "a" with "e" in the string "banana"

you are not really far :)

"banana".replace("a", "e")

Unless you meant, whithout using the str.replace function :) in which case here's the algorithm

def replace(str, old_char, new_char):
    return ''.join([c if c != old_char else new_char for c in str])

If for whatever reason you need to avoid using str.replace (YUCK I hate artificial requirements) you can wrap it up in a list comprehension.

NEW_CHAR = 'e'
OLD_CHAR = 'a'

''.join([NEW_CHAR if c == OLD_CHAR else c for c in "banana"])

Single-character replacements are best left to str.translate() :

try:
    # Python 2
    from string import maketrans
except ImportError:
    # Python 3
    maketrans = str.maketrans


def replace(original, char, replacement):
    map = maketrans(char, replacement)
    return original.translate(map)

str.translate() is by far the fastest option for per-character replacement mapping.

Demo:

>>> replace("banana", "a", "e")
'benene'

This supports mapping multiple characters, just make sure that both the char and replacement arguments are of equal length:

>>> replace("banana", "na", "so")
'bososo'
>>> replace("notabene", "na", "so")
'sotobese'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM