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)
2 Answers 2
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
-
This doesn't help if the user inputs
yoli
(he'll still getyxxlxx
).mgilson– mgilson2012年09月24日 15:35:42 +00:00Commented Sep 24, 2012 at 15:35 -
it's a bit weird of a requirement ... (using
count
onstr.replace
was my first intuition as well)mgilson– mgilson2012年09月24日 15:38:50 +00:00Commented 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).mgilson– mgilson2012年09月24日 15:40:52 +00:00Commented Sep 24, 2012 at 15:40
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'
homework
tag has recently been deprecated. See here.