简体   繁体   中英

Remove specific characters from a string

I want to remove all vowels from a string that the user gives. Below is my code and what I get as an output. For some reason the for loop is only checking the first character and nothing else.

Code:

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

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

print (sentence)

Output:

hello world

I have the print(x) just to make sure it was looking at all the characters and looping the character amount. However when the loop reaches a vowel it doesn't seem to be doing what I want, which is remove it from the string.

That's working as expected. strip is defined as:

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM