2

I am attempting to replace multiple letters within a string, I want the vowels to be replaced by the users input, and my current code replaces all the vowels with the same letters, however I want to replace the vowels with different user inputs. Below is an example of what I would like, and the code below that.

What I want

input1 = zz input2 = xx input3 = yolo output = yzzlxx 

What I have

input1 = zz input2 = xx input3 = yolo output = yzzlzz 

Here is my code.

def vwl(): syl1 = input("Enter your first syllable: ") syl2 = input("Enter the second syllable: ") translate = input("Enter word to replace vowels in: ") for ch in ['a','e','i','o','u']: if ch in translate: translate=translate.replace(ch,syl1,) for ch in ['a','e','i','o','u']: if syl1 in translate: translate=translate.replace(ch,syl2,) print (translate) 
3
  • Ryan: Is this a homework question that you are doing? If so, please use the "homework" tag. Commented Sep 24, 2012 at 15:30
  • 4
    @MarkHildreth: actually, the homework tag has recently been deprecated. See here. Commented Sep 24, 2012 at 15:31
  • What determines which inputs replace which vowels? Commented Sep 24, 2012 at 16:14

2 Answers 2

3

The method replace takes an additional argument count:

translate=translate.replace(ch,syl1,1) break # finish the for loop for syl1 

will only replace the first instance of ch and break will ensure you don't replace any subsequent vowels with syl1.

Similarly:

translate=translate.replace(ch,syl2,1) break # finish the for loop 
Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't help if the user inputs yoli (he'll still get yxxlxx).
it's a bit weird of a requirement ... (using count on str.replace was my first intuition as well)
Yes, I think that does it. (I'm glad you didn't delete your answer. I like to avoid re when possible) (+1).
3

You can use regular expressions:

translate = re.sub('a|e|i|o|u',input1,translate,count=1) translate = re.sub('a|e|i|o|u',input2,translate,count=1) 

Example:

>>> input1 = 'zz' >>> input2 = 'xx' >>> translate = 'yolo' >>> import re >>> translate = re.sub('a|e|i|o|u',input1,translate,count=1) >>> translate 'yzzlo' >>> translate = re.sub('a|e|i|o|u',input2,translate,count=1) >>> translate 'yzzlxx' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.