首页 > 解决方案 > 如何更改未指定的位置字符串?

问题描述

我想从我的字符串中删除元音并添加“。” 在其他字母之前。

我的代码

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'

标签: pythonstring

解决方案


您看到打印多个语句的原因是因为您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'))

推荐阅读