Python中的strip
是字符串对象的内置方法,用于移除字符串开头和结尾的指定字符(默认为空格)。以下是具体说明:
-
功能说明
strip
方法仅删除字符串的 首尾 字符,不会影响中间内容。例如:s = ' hello world ' stripped = s.strip() print(stripped) # 输出: 'hello world'
若指定字符参数,如
s.strip('123')
,则仅删除首尾的123
。 -
语法与参数
-
语法:
str.strip([chars])
-
chars
:可选参数,指定要删除的字符序列。若未传入参数,则默认删除空格、制表符、换行符等空白字符。
-
-
返回值
返回一个新的字符串,原字符串保持不变。例如:
s = ' hello world ' stripped = s.strip() print(s) # 仍输出: ' hello world ' print(stripped) # 输出: 'hello world'
-
扩展方法
-
lstrip([chars])
:仅删除左侧字符 -
rstrip([chars])
:仅删除右侧字符
-
-
应用场景
常用于数据清洗,例如去除文件路径中的多余空格,或处理用户输入时去除首尾的换行符等。
示例代码 :
s = ' 12345 '
print(s.strip()) # 输出: '12345'
print(s.strip('12')) # 输出: '345'
print(s.lstrip('1')) # 输出: '2345'
print(s.rstrip('5')) # 输出: ' 1234'