python - 如何更改未指定的位置字符串?
问题描述
我想从我的字符串中删除元音并添加“。” 在其他字母之前。
我的代码
x = input()
y = x.lower()
for h in y :
if h == 'a' or h == 'e' or h == 'i' or h == 'u' or h == 'o' :
new = y.replace('a' ,'')
new1 = new.replace('i','')
new2 = new1.replace('o','')
new3 = new2.replace('e','')
new4 = new3.replace('u','')
new5 = '.'.join (new4)
new6 = '.' + new5[0:]
print(new6)
else:
z = '.'.join(y)
r = '.' + z[0:]
print(r)
运行程序
hello
.h.e.l.l.o
.h.l.l
.h.e.l.l.o
.h.e.l.l.o
.h.l.l
我想要'.h.l.l'
。
解决方案
您看到打印多个语句的原因是因为您print
在循环的每次迭代中都进行了调用。
但是,更大的问题是您没有掌握单个迭代的结果。
这是你的循环应该是这样的:
new_word=y
for h in y:
if h in ('a','e','i','o','u'):
new_word=new_word.replace(h,'')
else:
new_word=new_word.replace(h,'.'+h)
但是,有一种更清洁的方法可以完成您想要的。
new_word=[c for c in y if c not in ('a','e','i','o','u')] # remove all vowels and convert to a list
new_word='.'.join(new_word) # since we only have consonants left, put periods in between them
if new_word: # if the word isn't empty, then we need a period before its first letter
new_word='.'+new_word
或者,在一行中:
new_word=''.join('.'+c for c in y if c not in ('a','e','i','o','u'))
推荐阅读
- javascript - 猫鼬喜欢 SQL Distinct 与最新日期
- ios - 在 SwiftUI 中监听 AVPlayer timeControlStatus 的变化
- java - 面向对象的Java:使用变量引用调用外部方法
- php - 图像缩放到新宽度并保持质量和纵横比
- java - 从 Modelclass 层次结构的顶层调用 setter
- php - 小数点前 9 位和小数点后 1 到 3 位数字的正则表达式
- automation - 如何通过小袋鼠自动化浏览器回滚数据库中所做的更改
- postgresql - 如何在不嵌套输出的情况下将模型包含在 sequelize 中
- php - 将帖子与用户 ID 一起存储,参考 Laravel 6 中的用户表
- java - swt中的Scrollable和ScrolledComposite有什么区别?