Home > OS >  Multiplicate vowels in a string with a number defined by the user
Multiplicate vowels in a string with a number defined by the user

Time:12-11

I'm new to Python and I need to multiplicate the vowels in a string with the number that the user gives me. For example:

new_string ("Charleston", 2)

Output: Chaarleestoon

I'm trying with this

def new_string (string, numero):
    vocales = "aeiou"
    sustituto = string*numero
    for vocales in vocales:
        string = string.replace(vocales, sustituto)
    print (string)

new_string("Charleston", 3)

But I don't have the result I want. Any help?

Thank you! Joana.

I'm trying with this

def new_string (string, numero): vocales = "aeiou" sustituto = string*numero for vocales in vocales: string = string.replace(vocales, sustituto) print (string)

new_string("Charleston", 3)

And I'm expecting this:

new_string ("Charleston", 2)

Output: Chaarleestoon

CodePudding user response:

One concise way of doing this would be to use a regex replacement with a lambda function:

import re

def new_string (string, numero):
    return re.sub(r'[aeiou]', lambda m: m.group()*numero, string, flags=re.I)

print(new_string("Charleston", 3))  # Chaaarleeestooon
  • Related