python stripline
时间: 2023-10-16 11:20:53 浏览: 34
`strip()` 是 Python 字符串方法之一,去除字符串开头和结尾的空格或指定字符,默认情况下去除空格。而 `strip()` 方法的变种 `lstrip()` 和 `rstrip()` 可以分别去除字符串左侧或右侧的空格或指定字符。
`strip()` 方法的语法如下:
```python
str.strip([chars])
```
其中,`chars` 参数是可选的,用于指定要去除的字符。如果不指定 `chars` 参数,则默认去除字符串开头和结尾的空格。如果指定了 `chars` 参数,则会从字符串开头和结尾依次去除指定的字符,直到遇到第一个不在 `chars` 中的字符为止。
例如,使用 `strip()` 方法去除字符串开头和结尾的空格:
```python
>>> s = " hello world! "
>>> s.strip()
'hello world!'
```
使用 `lstrip()` 方法去除字符串左侧的空格:
```python
>>> s = " hello world! "
>>> s.lstrip()
'hello world! '
```
使用 `rstrip()` 方法去除字符串右侧的空格:
```python
>>> s = " hello world! "
>>> s.rstrip()
' hello world!'
```
指定 `chars` 参数去除指定的字符:
```python
>>> s = "hello world! "
>>> s.strip('!')
'hello world'
```
以上就是 `strip()` 方法及其变种的用法。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)