Problem:
The reason your code does not quite work is because you sometimes use s
and sometimes s2
. s.replace(s[l],"")
does nothing to s
- so every time you use it, s2
gets to be s
with one vowel replaced in it - the others vowels are taken as isfor s
.
The last vowel replaced is o
- so s2
becomes: Yu lve Pythn!
- u
and e
are still in it.
Your code fixed:
s = "You love Python!"
vowels = "aeiou"
s1 = ""
for c in s:
if c in vowels:
s1 = s1+c # produces new string every time
s = s.replace(c,"") # produces new string every time
print(s1+s) # ouoeoY lv Pythn!
Optimizations:
Do not iterate by index, iterate over the characters of a string directly. If you collect things from strings, avoid producing more strings, use a list instead. Strings are immuteable, every time you modify one it is constructed new.
Suboptimal:
You can use list comprehensions to get the chars into two lists, combine both lists and join them back into a string:
s = "You love Python!"
s1 = [x for x in s if x.lower() in "aeiou"] # gets vowels, order and capitalization is kept
s2 = [x for x in s if x.lower() not in "aeiou"] # gets all other characters
s3 = ''.join(s1+s2) # adds lists back together and makes it a continious string
print(s1)
print(s2)
print(s3)
Output:
['o', 'u', 'o', 'e', 'o']
['Y', ' ', 'l', 'v', ' ', 'P', 'y', 't', 'h', 'n', '!']
ouoeoY lv Pythn!
Disadvantage: you have to go over the whole string twice. A simple for loop can do it in one pass:
s = "You love Python!"
s1=[]
s2=[]
for c in s:
if c in "aeiou":
s1.append(c)
else:
s2.append(c)
s3 = ''.join(s1+s2)
print(s1)
print(s2)
print(s3)
Output is the same.
Doku: