Reputation:
I'm trying to replace the vowels of a given string with the index of the same. I'm trying to use .replace() and .index() but it doesn't work. I have something like this:
def vowels(w):
vowel = 'aeiou'
for i in w:
if i in vowel:
a = w.replace(i, w.index(str(w.find('aeiou'))))
return a
The idea is this:
input = 'Hi Everyone'
output = 'H1 3v5ry8n10'
Upvotes: 1
Views: 458
Reputation: 13498
In this situation using .replace()
isn't a good idea. Generally .replace()
will do an operation on all vowels in the string, but in this situation you want to replace each vowel with a very specific value. A generator comprehension with join
is better here:
vowels = set('aeiou')
s = "Hi Everyone"
replaced = ''.join(str(i) if c.lower() in vowels else c for i, c in enumerate(s))
print(replaced)
Output:
H1 3v5ry8n10
Upvotes: 2
Reputation: 624
replace
takes a 3rd argument telling it how many characters to replace. For your purposes you need to replace one each time.
index
will give you the position of a character and str
will make it a string.
Using lower
makes sure all cases are matched.
Replace used characters in w
to include duplicates. Make sure it a list and the replacement is not a single character so it works for all strings.
def vowels(w):
vowel = 'aeiou'
a = w
w = list(w)
for i in w:
if i.lower() in vowel:
a = a.replace(i, str(w.index(i)), 1)
w[w.index(i)] = 0
return a
In: Hi Everyone
Out: H1 3v5ry8n10
Upvotes: 0
Reputation: 3593
Keeping in mind @Craig Meier's comment, the easiest way to keep track of the position of an element while iterating, is using enumerate
. This makes the find
operation unnecessary, and the code simpler.
The most Pythonic way to do this is of course what @Primusa proposes, but I think there's value in showing a more step-by-step approach.
def vowels(w):
vowel = 'aeiou'
for pos, char in enumerate(w): # extract a character and remember its position
if char.lower() in vowel: # check if it belongs to the check set
w = w.replace(char, str(pos), 1) # replace just the first instance
return w
inp = 'Hi Everyone'
output = vowels(inp)
print(output)
Upvotes: 0