Python 中的 strip()、lstrip() 和 rstrip() 是字符串(str)类型的内置方法,用于去除字符串中指定字符(默认为空白字符)的副本。它们返回处理后的新字符串,原字符串保持不变。
1. strip([chars])
- 作用 :移除字符串 开头和结尾 指定的字符。
- 参数 chars(可选):指定要去除的字符集合(一个字符串,其中的每个字符都会被去除)。如果不提供 chars,则默认去除空白字符(空格、换行 \n、制表符 \t 等)。
- 示例 :
python
s = " hello world \n"
print(s.strip()) #输出:"hello world"(去掉了两端的空格和换行)
t = "***hello***world***"
print(t.strip('*')) #输出:"hello\*\*\*world"(只去掉开头和结尾的\*,中间的保留)
2. lstrip([chars])
- 作用 :仅移除字符串 开头 指定的字符。
- 参数 chars 含义同上,默认为空白字符。
- 示例 :
python
s = " hello world "
print(s.lstrip()) #输出:"hello world "(去掉了开头的空格,结尾保留)
t = "www.example.com"
print(t.lstrip('w.')) #输出:"example.com"(去掉开头所有'w'和'.',直到遇到'e')
3. rstrip([chars])
- 作用 :仅移除字符串 结尾 指定的字符。
- 参数 chars 含义同上,默认为空白字符。
- 示例 :
python
s = " hello world "
print(s.rstrip()) #输出:" hello world"(去掉了结尾的空格,开头保留)
t = "filename.txt"
print(t.rstrip('.txt')) #输出:"filename"(去掉结尾的".txt")