2017-10-08 127 views
3

请告知下列代码是否有效。我似乎根本不工作立即替换字符串中的多个字符

string = str(input('Enter something to change')) 
replacing_words = 'aeiou' 

for i in replacing_words: 
    s = string.replace('replacing_words', ' ') 

print(s) 

这里我的意图是用空格替换字符串中的所有元音。 如果这是一个错误的代码,有人可以帮助正确的代码和解释,为什么它不工作?

谢谢

回答

2
  • 您在使用for循环中文字“replacing_words”,而不是变量i。
  • 你不用更换原来的字符串再次进行修改,而不是创建一个新的字符串,导致只有上次更换到显示

这里将是正确的代码。

string = input('Enter something to change') 
vowels = 'aeiouy' 

for i in vowels: 
    string = string.replace(i, ' ') 

print(string) 

此外,我认为输入返回一个字符串'类型'。所以调用str将不起作用。不确定。也#2:y也是元音(如果你想彻底的话,还有其他变音和怪异的字符)。

1

您正在错误地使用replace方法。由于您要分别替换每个字符,因此每次都应该传递一个字符。

这里是一个单行,做的伎俩:

string = ''.join(' ' if ch in vowels else ch for ch in string) 
+0

如果'str'先前没有定义(并且由于它影响了内建函数,它会是一个错误的名称选择),那么这会在'.replace'调用中出错。另外 - 那个list-comp是错的......所以这个要么不会运行,要么不会运行...... –

+0

@JonClements,谢谢你的评论,修正。 –

+0

map/lambda有点矫枉过正,但它现在至少可以工作 - 你是否只考虑过'''.join(''如果ch在元音其他字符串中ch')? –

1

试试这个代码:

string=raw_input("Enter your something to change") 
replacing_words = 'aeiou' 
for m in replacing_words: 
    string=string.replace(m, ' ') 
print string 
3

你可以定义一个translation table。这是一个Python2代码:

>>> import string 
>>> vowels = 'aeiou' 
>>> remove_vowels = string.maketrans(vowels, ' ' * len(vowels)) 
>>> 'test translation'.translate(remove_vowels) 
't st tr nsl t n' 

它快速,简洁,不需要任何循环。

对于Python3,你会写:

'test translation'.translate({ord(ch):' ' for ch in 'aeiou'}) # Thanks @JonClements. 
+1

在Python 3上,您可以使用:''test translation.translate({ord(ch):''for'aeiou'})'... –

0

在Python中,字符串是不可变的。

# Python 3.6.1 

""" Replace vowels in a string with a space """ 

txt = input('Enter something to change: ') 
vowels = 'aeiou' 
result = '' 

for ch in txt: 
    if ch.lower() in vowels: 
     result += ' ' 
    else: 
     result += ch 

print(result) 

测试它:

Enter something to change: English language 
ngl sh l ng g 

在Python 3。X,你也可以写(没有进口):

vowels = 'aeiouAEIOU' 
space_for_vowel = str.maketrans(vowels, ' ' * len(vowels)) 
print('hello wOrld'.lower().translate(space_for_vowel)) 

h ll w rld 
0

您可以在字符串首先检查的话是元音字符串,然后替换:

string = str(input('Enter something to change')) 

replacing_words = 'aeiou' 

for i in string: 
    if i in replacing_words: 
     string=string.replace(i," ") 

print(string) 

如果你想保持原来的复制和也想改变字符串,则:

string = str(input('Enter something to change')) 
string1=string[:] 
replacing_words = 'aeiou' 

for i in string1: 
    if i in replacing_words: 
     string1=string1.replace(i," ") 

print("{} is without vowels : {} ".format(string,string1)) 

输出:

Enter something to change Batman 
Batman is without vowels : B tm n