strip 函数
一、概述
strip 函数是 Python 字符串操作中常用的函数,它用于去除字符串开头和结尾的空格或指定字符。在实际应用中,我们经常需要对用户输入的字符串进行处理,去除多余的空格或特殊字符,以便进行后续操作。本文将详细介绍 strip 函数的使用方法和注意事项。
二、语法格式
strip 函数的语法格式如下所示:
str.strip([chars])
其中,str 表示要处理的字符串;chars 表示要去除的字符集合。如果不指定 chars 参数,则默认去除字符串开头和结尾的空格。
三、使用方法
1. 去除开头和结尾的空格
当不指定 chars 参数时,strip 函数默认去除字符串开头和结尾的空格。例如:
```
str = '  hello, world!  '
print(str.strip())
```
输出结果为:'hello, world!'。
2. 去除指定字符集合
如果需要去除字符串中指定的字符集合,则可以在 chars 参数中指定这些字符。例如:
```
str = '---hello, world!---'
print(str.strip('-'))
```
输出结果为:'hello, world!'。
3. 指定去除开头或结尾字符
strip 函数还可以通过 lstrip 和 rstrip 方法分别指定只去除开头或结尾的字符。例如:
```
str = '***hello, world!***'
print(str.lstrip('*'))
print(str.rstrip('*'))
```
输出结果分别为:'hello, world!***' 和 '***hello, world!'。
四、注意事项
1. strip 函数不会改变原有字符串的值,而是返回一个新的字符串。
2. 如果指定的字符集合中包含空格,则只会去除开头和结尾的空格,而不会去除中间的空格。
3. 如果需要去除字符串中间的空格,可以使用 replace 函数将空格替换成空字符。例如:字符串replace函数
```
str = 'hello,    world!'
place(' ', ''))
```
输出结果为:'hello,world!'。
五、示例代码
下面是一个完整的示例代码,演示了 strip 函数的各种用法:
```
def strip_demo():
    str1 = '  hello, world!  '
    str2 = '---hello, world!---'
    str3 = '***hello, world!***'
    str4 = 'hello,    world!'
   
    print('去除开头和结尾的空格:')
    print(str1.strip())
   
    print('去除指定字符集合:')
    print(str2.strip('-'))
   
    print('指定只去除开头或结尾字符:')
    print(str3.lstrip('*'))
    print(str3.rstrip('*'))
   
    print('替换字符串中间的空格:')
    place(' ', ''))
if __name__ == '__main__':
  strip_demo()
```