0

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"

2
  • 3
    I suggest using string.replace. Or did you mean "without using the string function or anything like string.replace"? In any case, show us the code you've written so far. Commented Apr 9, 2014 at 17:56
  • yes how could i do it WITHOUT string.replace? Commented Apr 9, 2014 at 17:59

3 Answers 3

5

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])
Sign up to request clarification or add additional context in comments.

8 Comments

how could i do this without .replace?
@SamyArous str.join actually works faster with a list comp than a gen comp, but yuck you're shadowing str() in that function!
i did edit my question, now we haven't learned about .join so I'm not completely sure how it works.
@AdamSmith yes, I have to get rid of this bad habit :)
@SamyArous I'm working on chucking it as well. Generators are faster for darn near everything else, just not str.join :D
|
2

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'

1 Comment

It works with multiple characters as well if you want ... (+1 this is the right if not necessarily obvious solution imho)
2

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"])

2 Comments

while you can certainly use a generator, its actually faster to use a list if you dont need to use a generator for space reasons ... (+1)
I was originally responding to @SamyArous's now deleted comment ... yes you are using a list :P (I gave you +1 also :P)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.