Python中字符串方法strip()的用法与常见疑问

print('abdpab sa'.strip('pab'))

为什么结果是:'dpab s'


Python中字符串方法strip()的用法与常见疑问
4 回复

Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

好好理解最后一句


strip() 是 Python 字符串处理里最基础也最常用的方法之一,但新手确实容易对它的行为产生误解。简单来说,strip() 默认移除字符串首尾的空白字符(包括空格、换行符 \n、制表符 \t 等)。它不会处理字符串中间的任何字符。

核心用法:

# 1. 基本用法:去除首尾空白字符
text = "  Hello, World!  \n"
print(text.strip())  # 输出: "Hello, World!"

# 2. 指定要移除的字符:可以传入一个字符串参数,它会将参数中每个字符都视为需要移除的目标
text = "***Hello!***"
print(text.strip("*"))  # 输出: "Hello!"

# 3. 只处理一端:lstrip() 只处理开头,rstrip() 只处理结尾
text = "  Hello  "
print(text.lstrip())  # 输出: "Hello  "
print(text.rstrip())  # 输出: "  Hello"

最常见的两个疑问:

  1. “为什么中间的字符去不掉?” 这是对 strip() 功能最大的误解。它的设计就是只处理两端。如果你想移除所有特定字符,需要用 replace() 或正则表达式 re.sub()

    text = "aabbaabbaa"
    print(text.strip("a"))  # 输出: "bbaabb" (只去掉了首尾的'a')
    print(text.replace("a", ""))  # 输出: "bbbb" (去掉了所有的'a')
    
  2. “参数 chars 是子字符串还是字符集合?” 它是字符集合strip("abc") 会不断移除首尾出现在集合 {'a', 'b', 'c'} 中的字符,直到遇到一个不在此集合的字符为止。

    text = "abc123cba"
    print(text.strip("abc"))  # 输出: "123" (首尾的a,b,c都被移除了)
    # 注意:它不是在找子串"abc",而是分别移除'a','b','c'这些字符
    

一句话总结: 记住 strip() 是“剃头修脚”,不动中间,且参数是字符黑名单。

原来如此,谢谢

1 Docstring for builtins:function strip
2 ========================================
3 S.strip([chars]) -> str
4
5 Return a copy of the string S with leading and trailing
6 whitespace removed.
7 If chars is given and not None, remove characters in chars instead.

回到顶部