立即替换字符串中的多个字符
问题描述:
请告知下列代码是否有效。我似乎根本不工作立即替换字符串中的多个字符
string = str(input('Enter something to change'))
replacing_words = 'aeiou'
for i in replacing_words:
s = string.replace('replacing_words', ' ')
print(s)
这里我的意图是用空格替换字符串中的所有元音。 如果这是一个错误的代码,有人可以帮助正确的代码和解释,为什么它不工作?
谢谢
答
- 您在使用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也是元音(如果你想彻底的话,还有其他变音和怪异的字符)。
答
您正在错误地使用replace
方法。由于您要分别替换每个字符,因此每次都应该传递一个字符。
这里是一个单行,做的伎俩:
string = ''.join(' ' if ch in vowels else ch for ch in string)
答
试试这个代码:
string=raw_input("Enter your something to change")
replacing_words = 'aeiou'
for m in replacing_words:
string=string.replace(m, ' ')
print string
答
你可以定义一个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'})'... –
答
在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
答
您可以在字符串首先检查的话是元音字符串,然后替换:
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
如果'str'先前没有定义(并且由于它影响了内建函数,它会是一个错误的名称选择),那么这会在'.replace'调用中出错。另外 - 那个list-comp是错的......所以这个要么不会运行,要么不会运行...... –
@JonClements,谢谢你的评论,修正。 –
map/lambda有点矫枉过正,但它现在至少可以工作 - 你是否只考虑过'''.join(''如果ch在元音其他字符串中ch')? –