我正在尝试从给定单词中删除元音并返回单词。
例如
word = "helleeEoo"
如果我使用如下所示的 strip 命令,我得到的输出是“hell”而不是“hll”
word = word.strip("aAeEiIoOuU")
但如果我使用如下所示的连接命令,它就可以正常工作:
word = ''.join(c for c in word if c not in 'aAeEiIoOuU')
我正在使用 python 3,我想知道为什么在 strip 命令的情况下最终输出中存在“e”?
请您参考如下方法:
来自docs (强调我的):
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. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:
...
The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end.
未被 strip 删除的“e”不在字符串的两端。它在中间,因此 strip 不会碰到它。
在您的第二个示例中,c for c in word 触及字符串中的每个字符,因此触及中间的“e”,由 not in 测试, 并省略。
