0

I'm trying to create a function that accepts a string and replaces the vowels with other characters.

I've written some code, but when I run it in IDLE the output is 'None', but I'm expecting it to be '44 33 !! ooo000 ||||'

I have the below:

def vowel_swapper(string):
    for char in string:
        if char in 'aeiouAEIOU':
            char.replace('a', '4').replace('A', '4').replace('e', '3').replace('E', '3')\
            .replace('i', '!').replace('I', '!').replace('o', 'ooo').replace('O', '000').replace('u', '|_|').replace('U', '|_|')

print(vowel_swapper("aA eE iI oO uU"))

Where have I gone wrong here?

Edit: Thanks for all of the responses. I will also take on the advice about using a dictionary and look into it.

  • First of all, your `vowel_swapper` function doesn't return anything, so you can expect your print statement to print `None` (functions that don't explicitly return something always implicitly return `None`). You also haven't shown the entirety of the `vowel_swapper` function, so I'm assuming the first few lines of your code snippet make up the body of that function. Also, strings are immutable in python, and `str.replace` doesn't modify a string in-place. Additionally, there is no need to iterate over the characters in your string. Simply use `return string.replace(...).replace(...)...` – Paul M. Jul 10 '20 at 10:59
  • using `str.replace()` constructs in each call new string copy. this solution is enefficeient. if you dont have to use replace method then this we can solve it in list comrehension without the ovverhead of replace – Adam Jul 10 '20 at 11:03
  • learn about regex, but note https://docs.python.org/3/howto/regex.html#common-problems , this will help you https://www.debuggex.com/?flavor=python , welcome to a world of pleasure and pain... Almost all languages have a version of "Regular Expressions" so worth knowing! – Tyeth Jul 10 '20 at 11:40

8 Answers8

1

In python, .replace is not a in place modification. It returns the result of said modification rather than doing an in place modification.

For what you want to achieve, you cannot do it while looping through the string and possibly assigning each changed char to the string. Python strings are immutable.

Instead, you should do-

def vowel_swapper(s: str):
    return s.replace('a', '4').replace('A', '4').replace('e', '3').replace('E', '3').replace('i', '!').replace('I', '!').replace('o', 'ooo').replace('O', '000').replace('u', '|_|').replace('U', '|_|')

Which will replace all the characters you want to replace at once and return the result.

Output-

44 33 !! ooo000 |_||_|

A more elegant approach however, would be to use a dict.

def vowel_swapper(s: str):
    replacements = {'a': '4', 'A': '4', 'e': '3', 'E': '3', 'i': '!', 'I':  '!', 'o': 'ooo', 'O': '000', 'u': '|_|', 'U': '|_|'}
    return "".join([replacements.get(c, c) for c in s])

Output-

44 33 !! ooo000 |_||_|

Here, we're using .get (with a default value) to efficiently and pythonically, replace and map each character in given string

Chase
  • 5,315
  • 2
  • 15
  • 41
1

You are looping through the string and not updating the value of the characters in the string with the replace method.

You can use:

def vowel_swapper(string):
     return string.replace('a', '4').replace('A', '4').replace('e', '3').replace('E', '3').replace('i', '!').replace('I', '!').replace('o', 'ooo').replace('O', '000').replace('u', '|_|').replace('U', '|_|')

vowel_swapper("aA eE iI oO uU")

May I suggest a another way to approach the problem that uses dictionary instead of using replace method multiple times?

string= "aA eE iI oO uU xx"
swap_dic= {'a':'4', 'e':'3','i':'!','o':'000','u':'|_|' }

string= string.lower()

for char in string:
    if char in swap_dic.keys():
        string= string.replace(char,swap_dic[char])
    
print(string)
0

you don't need to check every character whether they are a vowel or not while using replace, as str.replace return the replace new string with all the replace character with new one

def vowel_swapper(string):

    res = string.replace('a', '4').replace('A', '4').replace('e', '3').replace('E', '3')\
            .replace('i', '!').replace('I', '!').replace('o', 'ooo').replace('O', '000').replace('u', '|_|').replace('U', '|_|')

    return res
print(vowel_swapper("aA eE iI oO uU"))

output

44 33 !! ooo000 |_||_|
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0

The replace method works on entire strings, and returns a new string.

You can save time by converting your string to lowercase, almost halving the methods called.

def vowel_swapper(string):
    return string.replace('o', 'ooo').replace('O', '000').lower().replace('a', '4').replace('e', '3').replace('u', '|_|')
dwb
  • 2,136
  • 13
  • 27
0

As an alternative to doing replace().replace().replace()... you can use str.maketrans() on a dict() of replacement characters then run translate() on the string:


def vowel_swapper(string):
    table = str.maketrans({'a': '4', 'A': '4',
                           'e': '3', 'E': '3',
                           'i': '!', 'I': '!',
                           'o': 'ooo', 'O': '000',
                           'u': '|_|', 'U': '|_|',
                           }
                          )

    return string.translate(table)


print(vowel_swapper("aA eE iI oO uU"))

Output:

44 33 !! ooo000 |_||_|
Terry Spotts
  • 3,527
  • 1
  • 8
  • 21
0
def vowel_swapper(stringer):
    new_str = ""
    for char in stringer:
        char = char.replace("A", "4")       # 
These replace the characters
        char = char.replace("E", "3")       # 
Char.replace returns a value rather than resets 
the value of the string it is used on 
        char = char.replace("I", "!")
        char = char.replace("O", "000")
        char = char.replace("U", "|_|")
        char = char.replace("a", "4")
        char = char.replace("e", "3")
        char = char.replace("i", "!")
        char = char.replace("o", "ooo")
        char = char.replace("u", "|_|")

        print(char)
        new_str = new_str + char        # 
creating and building a new string to return 
    return new_str
    
print(vowel_swapper('aA eE iI oO uU'))

when using char.replace() remember it is a method so you get a value out of it.

also your function did not return a value.

:)

Dom
  • 9
  • 4
0

Use the letters needed to be removed from the string in dict (we can access the dict in O(1) time complexity)

popouts = {'a': '4', 'A': '4', 'e': '3', 'E': '3', 'i': '!', 'I':  '!', 'o': 'ooo', 'O': '000', 'u': '|_|', 'U': '|_|'}

our input string for example:

sst="fpooabraabdbuuososso"
splited_str=(" ".join(sst)).split()


for j in range(len(splited_str)):
  if splited_str[j] in popouts:
    splited_str[j]=(popouts[splited_str[j]])

final_string="".join(splited_str)
Adam
  • 2,820
  • 1
  • 13
  • 33
0
def rep_vowels(vs):
    for i in vs:
        if i in "aeiouAEIOU":
            return vs.replace("a", "*").replace("A", "*").replace("e", "*").replace("E", "*").replace("I", "*").replace("i","*").replace("o","*").replace("O", "*").replace("u", "*").replace("U", "*")

print(rep_vowels("COMPUTER"))  

I've replaced it with star(shift+8)

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Deminous
  • 1
  • 3
  • 1
    Welcome to Stack Overflow! While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Sep 12 '21 at 09:24
  • Welcome to Stack Overflow! You made another important change to your code that you haven't explained to OP, something you did that he forgot. You should include that in your answer. – hamsolo474 - Reinstate Monica Sep 12 '21 at 09:50