9

I want to replace every character that isn't "i" in the string "aeiou" with a "!"

I wrote:

def changeWord(word):
    for letter in word:
        if letter != "i":
            word.replace(letter,"!")
    return word

This just returns the original. How can I return "!!i!!"?

6 Answers 6

13

Strings in Python are immutable, so you cannot change them in place. Check out the documentation of str.replace:

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

So to make it work, do this:

def changeWord(word):
    for letter in word:
        if letter != "i":
            word = word.replace(letter,"!")
    return word
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, I see. Should've realized that. Thank you!
While this'll work, it's worst-case O(len(word)^2). Something like ''.join('!' if c != 'i' else c for c in word) would be more efficient for long strings.
This is an O(n^2) algorithm… It's not wrong, just inefficient
8

Regular expressions are pretty powerful for this kind of thing. This replaces any character that isn't an "i" with "!"

import re
str = "aieou"
print re.sub('[^i]', '!', str)

returns:

!!i!!

Comments

3

something like this using split() and join():

In [4]: strs="aeiou"

In [5]: "i".join("!"*len(x) for x in strs.split("i"))
Out[5]: '!!i!!'

Comments

3

Try this, as a one-liner:

def changeWord(word):
    return ''.join(c if c == 'i' else '!' for c in word)

The answer can be concisely expressed using a generator, there's no need to use regular expressions or loops in this case.

Comments

2

Nobody seems to give any love to str.translate:

In [25]: chars = "!"*105 + 'i' + "!"*150

In [26]: 'aeiou'.translate(chars)
Out[26]: '!!i!!'

Hope this helps

2 Comments

@RocketDonkey: I must admit though, that this would be inefficient for small translations in small inputs. It works here to avoid a str.join and because there is a LOT of translation :)
Haha, well it is still a cool a solution - I'm sure someone will get use out of it.
0

Generally in python string are immutable that means it can't be changed after its creation. So we have to convert string into mutable and that can be possible using list as it is mutable.

string="Love"

editable = list(string)
editable[2]='s'
string=''.join(editable)

output:Lose

Comments

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.