从字符串中删除特定字符 [英] Remove specific characters from a string

查看:70
本文介绍了从字符串中删除特定字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从用户提供的字符串中删除所有元音.下面是我的代码和我得到的输出.出于某种原因,for 循环只检查第一个字符而不检查其他字符.

代码:

sentence = "Hello World."句子 = 句子.lower()对于 x 在句子中:句子 = sentence.strip("aeiou")打印 (x)打印(句子)

输出:

你好世界

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

解决方案

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

<块引用>

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

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

正如它所说,它只影响前导和尾随字符 - 一旦找到不在要删除的字符集中的字符,它就会停止查找.无论如何,粗略地说;我没有检查实际实现的算法.

我认为 translate 是最有效的方法.来自文档:

<预><代码>>>>'阅读这篇短文'.translate(None, 'aeiou')'rd ths shrt txt'

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

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

这篇关于从字符串中删除特定字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆