Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...