Skip to content
Advertisement

how do I create a function that randomly replaces vowels in a string with * in python

def long_string(str):
    vow_list = ["a","e","i","o","u"]

    for v in vow_list:
        new_str = str.replace(v,"*")
        return(new_str)

long_string("Why is this code not working?")

Advertisement

Answer

Answered according to the comment clarification: pick a random vowel, replace all occurences of this vowel.

import random

text = "Why is this code not working?"
vowels = "aeiouAEIOU"
vowel = random.choice(vowels)
text.replace(vowel, "*")

random.choice picks a random element from a sequence. Strings are also sequences, and "aeiou" looks prettier (and is slightly, very slightly more memory-efficient, though this is a non-issue) than ["a","e","i","o","u"].

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement