简体   繁体   English

从字符串中删除特定字符

[英]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. 由于某些原因,for循环仅检查第一个字符,而没有其他检查。

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. 我有print(x)只是为了确保它正在查看所有字符并循环显示字符数量。 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: strip定义为:

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. chars参数是一个字符串,指定要删除的字符集。

http://docs.python.org/2/library/stdtypes.html#str.strip 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. 我认为translate是最有效的方法。 From the docs: 从文档:

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

http://docs.python.org/2/library/stdtypes.html#str.translate 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 函数id()给定的地址差异意味着对象xyz是不同的对象,位于RAM中的不同位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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