Aei
Aei

Reputation: 705

How do I replace a character in a string with another character in Python?

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!!"?

Upvotes: 9

Views: 40642

Answers (6)

SaimumIslam27
SaimumIslam27

Reputation: 1188

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

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113905

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

Upvotes: 2

Óscar López
Óscar López

Reputation: 235984

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.

Upvotes: 3

Rachel Sanders
Rachel Sanders

Reputation: 5874

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!!

Upvotes: 8

JoelWilson
JoelWilson

Reputation: 414

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

Upvotes: 13

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

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!!'

Upvotes: 3

Related Questions