为什么 split 和 strip 在 python 中给出不同的输出?

Why split and strip gives different output in python?

我试图从字符串 'Rhode Island[edit]' 中提取州名称。

当我尝试 .split('[[]').str[0] 时,得到了正确的结果 'Rhode Island'。 然而,当我尝试 .rstrip('[edit]') 时,得到了错误的结果 'Rhode Islan'.

我很困惑为什么我使用rstrip函数时左括号前的字符'd'也被删除了。

rstrip 没有做你想做的,它删除了字符串末尾指定的所有字符,所以它删除了 '[', 'e', 'd', 'i'、't' 和“]”。你想要的是拆分 '[' 然后取第一个元素:'Rhode Island[edit]'.split('[')[0]

S.rstrip([chars]) -> 字符串或 unicode

Return 删除尾随空格的字符串 S 的副本。 如果给出的是 chars 而不是 None,则移除 chars 中的字符。 如果chars是unicode,S会在剥离前转换成unicode

在你的情况下,字符 = ['[','e','d','i','t',']'] 其中包含 'd' 因此由给定字符形成的尾随字符串是 d[edit]

试试正则表达式

import re
re.compile(r'\[edit\]$').sub('','Rhode Island[edit]')