2

我想从用户提供的字符串中删除所有元音。下面是我的代码以及我得到的输出。出于某种原因,for 循环仅检查第一个字符而没有其他任何内容。

代码:

sentence = "Hello World."
sentence = sentence.lower()

for x in sentence:
    sentence = sentence.strip("aeiou")
    print (x)

print (sentence)

输出:

hello world

我有 print(x) 只是为了确保它正在查看所有字符并循环字符数量。然而,当循环到达一个元音时,它似乎并没有做我想要的,即将它从字符串中删除。

4

2 回答 2

3

这按预期工作。strip定义为:

返回删除了前导和尾随字符的字符串的副本。chars 参数是一个字符串,指定要删除的字符集。

http://docs.python.org/2/library/stdtypes.html#str.strip

So as it says, it only affects the leading and trailing characters - it stops looking as soon as it finds a character that isn't in the set of characters to strip. Loosely speaking, anyway; I didn't check the actual implementation's algorithm.

I think translate is the most efficient way to do this. From the docs:

>>> 'read this short text'.translate(None, 'aeiou')
'rd ths shrt txt'

http://docs.python.org/2/library/stdtypes.html#str.translate

于 2013-10-18T20:21:26.603 回答
0

You can't remove characters from a string: a string object is immutable. All you can do is to create a new string with no more wovels in it.

x = ' Hello great world'
print x,'  id(x) == %d' % id(x)

y = x.translate(None,'aeiou') # directly from the docs
print y,'  id(y) == %d' % id(y)

z = ''.join(c for c in x if c not in 'aeiou')
print z,'  id(z) == %d' % id(z)

result

 Hello great world   id(x) == 18709944
 Hll grt wrld   id(y) == 18735816
 Hll grt wrld   id(z) == 18735976

The differences of addresses given by function id() mean that the objects x, y, z are different objects, localized at different places in the RAM

于 2013-10-18T20:28:14.777 回答