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)
asked Sep 24, 2012 at 15:27
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
answered Sep 24, 2012 at 15:31
3
  • This doesn't help if the user inputs yoli (he'll still get yxxlxx). Commented Sep 24, 2012 at 15:35
  • it's a bit weird of a requirement ... (using count on str.replace was my first intuition as well) Commented Sep 24, 2012 at 15:38
  • Yes, I think that does it. (I'm glad you didn't delete your answer. I like to avoid re when possible) (+1). Commented Sep 24, 2012 at 15:40
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'
answered Sep 24, 2012 at 15:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.