str.strip()用法
时间: 2024-03-02 08:22:58 浏览: 26
`str.strip()` 是一个字符串方法,用于移除字符串两端的空白字符(包括空格、制表符和换行符)。该方法不会修改原始字符串,而是返回一个新字符串。
以下是 `str.strip()` 的使用示例:
```python
text = " hello, world! "
print(text.strip()) # 输出:hello, world!
text = "\t\t\tPython is awesome!\n\n"
print(text.strip()) # 输出:Python is awesome!
```
在这个例子中, `strip()` 方法移除了字符串的两端的空格和制表符,以及末尾的两个换行符。
相关问题
python str.strip()
`str.strip()`是Python中的一个字符串方法,用于去除字符串开头和结尾的空格或指定字符。具体来说,它会返回一个新的字符串,该字符串是原始字符串的副本,但开头和结尾的空格或指定字符已被删除。
以下是一些使用`str.strip()`的例子:
1. 去除字符串开头和结尾的空格:
```python
s = ' hello world '
print(s.strip()) # 输出:'hello world'
```
2. 去除字符串开头和结尾的指定字符:
```python
s = '---hello world---'
print(s.strip('-')) # 输出:'hello world'
```
3. 去除字符串开头的指定字符:
```python
s = '---hello world'
print(s.lstrip('-')) # 输出:'hello world'
```
4. 去除字符串结尾的指定字符:
```python
s = 'hello world---'
print(s.rstrip('-')) # 输出:'hello world'
```
str.strip()
str.strip() 是一个字符串方法,用于删除字符串开头和结尾的指定字符(默认为空格)。
使用示例:
```python
s = " hello world "
s = s.strip() # 删除开头和结尾的空格
print(s) # 输出:hello world
s = "---hello world---"
s = s.strip("-") # 删除开头和结尾的“-”
print(s) # 输出:hello world
```
在上面的示例代码中,第一个例子使用默认参数删除了字符串开头和结尾的空格,第二个例子则删除了开头和结尾的“-”字符。
str.strip() 方法还可以接受一个可选的参数chars,用于指定需要删除的字符。例如,如果我们想要删除字符串开头和结尾的所有空格、换行符和制表符,可以这样写:
```python
s = " \n\t hello world \t\n"
s = s.strip(" \n\t") # 删除开头和结尾的空格、换行符和制表符
print(s) # 输出:hello world
```
在这个例子中,我们将需要删除的字符作为 chars 参数传递给了 strip() 方法。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)