python删除字符串空白字符
时间: 2023-06-18 22:06:33 浏览: 67
在 Python 中,可以使用字符串函数 strip()、lstrip() 和 rstrip() 来删除字符串中的空白字符。
strip() 函数可以删除字符串两端的空白字符(包括空格、制表符和换行符)。例如:
```
string = " hello, world! \n"
new_string = string.strip()
print(new_string)
```
输出结果为:
```
hello, world!
```
如果只想删除字符串左边或右边的空白字符,可以使用 lstrip() 或 rstrip() 函数。例如:
```
string = " hello, world! \n"
new_string = string.lstrip()
print(new_string)
```
输出结果为:
```
hello, world!
```
```
string = " hello, world! \n"
new_string = string.rstrip()
print(new_string)
```
输出结果为:
```
hello, world!
```
相关问题
python去除字符串前后空白字符
可以使用字符串的 `strip()` 方法来去除字符串前后的空白字符。例如:
```python
s = " hello world "
s = s.strip()
print(s) # 输出 "hello world"
```
`strip()` 方法默认会去除字符串前后的空格、制表符、换行符等空白字符。如果你只想去除字符串开头或结尾的空白字符,可以使用 `lstrip()` 或 `rstrip()` 方法。例如:
```python
s = " hello world "
s = s.lstrip()
print(s) # 输出 "hello world "
s = " hello world "
s = s.rstrip()
print(s) # 输出 " hello world"
```
python去除字符串右边空白符
可以使用字符串的rstrip()方法去除右边的空白符,例如:
```python
s = " hello world "
s = s.rstrip()
print(s) # 输出 " hello world"
```
如果想删除指定字符,可以在rstrip()方法中传入需要删除的字符,例如:
```python
s = " hello world! "
s = s.rstrip("!")
print(s) # 输出 " hello world "
```