python - strip 命令不会删除字符串中的 'e'

标签 python python-3.x

我正在尝试从给定单词中删除元音并返回单词。

例如

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 测试, 并省略。

关于python - strip 命令不会删除字符串中的 'e',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43478590/

相关文章:

python - 检测最后一个子目录 os.walk()

python - 频率计数器在我更改之前正在排序列表,更改后应该何时排序

python-3.x - 如何在 sagemaker 中设置 NotebookApp.iopub_data_rate_limit

python-3.x - 类型错误 : unsupported operand type(s) for/: 'dict_values' and 'int'

python - "0-th value returned by pyfunc_0 is double, but expects float"虽然我认为它返回 float

python - 使用 Python 解析来自 AWS SDK 的 Cloudformation 字符串响应

python - 我可以在 tkinter 中使标签可点击并获得点击标签的值(value)吗?

python - 在 matplotlib 中编辑堆积条形图的 x 轴刻度标签

python - 卡住不允许识别模式的线程

django - 为什么 __init__() 和 get_context_data() 中对象的属性不同?