2014-12-05 46 views
0
s = input() 
s.lower() 
for i in range (0, len(s)): 
    if(s[i] in "aoyeui"): 
     s.replace(s[i], '') 
for i in range(0, len(s)): 
    s.replace(s[i], '.' + s[i]) 
print(s) 

此代碼應刪除所有元音並按'。'分割字符串。s.replace()調用在Python中沒有效果

+2

由於我們無法得知你在編寫代碼的屏幕,學究可能會說「縮進」 ...的[從字符串中刪除特定字符 – Makoto 2014-12-05 22:05:11

+0

可能重複蟒](http://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python) – 2014-12-05 22:27:26

回答

1

str是不可變的。所有操作都會創建一個新的str

當您使用replace時,您想重新指定s。或者lower

s = s.lower() 

s = s.replace(s[i], '') 
3

一行讓註釋就行:

s = input() #wrong indentation 
s.lower()  # you have to assign it to s. 
for i in range (0, len(s)): # range(0, x) is the same as range(x) 
    if (s[i] in "aoyeui"): # ok 
     s.replace(s[i], '') # strings are not mutable so replace does not modify the string. You have to assign it to s 
# splitting can be done much easier :) 
for i in range(0, len(s)): 
    s.replace(s[i], '.' + s[i]) # again you have to assign 
print(s) # ok 

另外我剛纔注意到,有更多的一個問題你的代碼。當您替換元音字符串長度更改時,它可能會導致多個問題。一般來說,當長度發生變化時,不應該按索引進行迭代。所以,正確的代碼應該是這樣的:

s = input() 
s = s.lower() 
for vowel in "aoyeui": 
     s = s.replace(vowel, '') 
s = '.'.join(list(s)) # this is how to separate each character with a dot (much easier eh?) 
print(s) 
0

s.lower()應分配給s否則原始的字符串將保持不變。

我重寫了一個工作代碼。希望它可以幫助你:

s = str(input("Text: ")) 
s = s.lower() 
t ="" 
for char in s: 
    if char not in "aoyeui": 
     t+=char 

t = t.split('.') 

for i in t: 
    print(i)