str.strip() python ,用法
时间: 2023-11-01 21:07:34 浏览: 47
str.strip() 是一个 Python 字符串方法,用于删除字符串开头和结尾的空格或指定的字符。如果未指定字符,则默认删除空格。
用法如下:
```
string.strip([chars])
```
参数说明:
- chars (可选):指定删除的字符。如果未指定或为 None,则删除开头和结尾的空格。
示例:
```python
string = " hello, world! "
print(string.strip()) # 输出:hello, world!
print(string.strip(" ")) # 输出:hello, world!
print(string.strip(" !")) # 输出:hello, world
```
在上面的示例中,第一个 strip() 方法将删除字符串开头和结尾的空格,第二个 strip() 方法将删除开头和结尾的空格,第三个 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()` 是一个字符串方法,用于移除字符串两端的空白字符(包括空格、制表符和换行符)。该方法不会修改原始字符串,而是返回一个新字符串。
以下是 `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()` 方法移除了字符串的两端的空格和制表符,以及末尾的两个换行符。