python去除字符串前后空白字符
时间: 2023-08-15 12:05:22 浏览: 57
可以使用字符串的 `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 "
```
python删掉字符串两边空白字符
在Python中,可以使用字符串的`strip()`方法来删除字符串两边的空白字符。`strip()`方法会返回一个新的字符串,该字符串是原始字符串去除两边空白字符后的结果。
以下是一个示例:
```python
string = " Hello, World! "
new_string = string.strip()
print(new_string) # 输出: "Hello, World!"
```
`strip()`方法还可以接受一个参数,用于指定要删除的字符。例如,如果想删除字符串两边的所有逗号和句点,可以这样使用:
```python
string = ",,Hello, World!.."
new_string = string.strip(",.")
print(new_string) # 输出: "Hello, World"
```