python - 有没有办法将字符串中存在的所有元音移到开头
问题描述
编写一个程序,接收一个字符串并将其中的所有元音移到开头。
我尝试将元音一一排序并在旅途中删除它们并分别保存两个字符串,然后最后我加入了它
s = "You love Python!"
vowels = "aeiou"
s1= ""
for l in range(0,len(s)):
if s[l] in vowels:
s1 = s1+s[l]
s2 = s.replace(s[l],"")
print(s1+s2)
输出 :
ouoeoYu lve Pythn!
但是在第二个单词的输出“e”中没有排序。错误是什么?
解决方案
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:
推荐阅读
- php - CURL 调用可以直接在 CURL 中正常工作,但在 PHP 7.3 中不能正常工作
- powerbi - DAX - 使用 SWITCH 格式化
- python - 使用 selenium 进行网页抓取以单击按钮并抓取所有内容
- python - Python:类型提示中的私有类型?
- javascript - 通过 fetch 在浏览器中使用 .vue 文件
- c# - 系统意外尝试连接到 localDb
- python - 为 pyinstaller 创建的 .exe 生成证书
- xslt - 打印列表中匹配元素的当前值
- wordpress - Woocommerce:使用特定付款方式下订单后不要清空购物车
- c++ - 类模板中的运算符重载