python去除字符串两端空格
时间: 2024-11-13 15:16:53 浏览: 5
Python去除字符串两端空格的方法
在Python中,你可以使用`strip()`函数来去除字符串两端的空格。这个方法会移除字符串首尾的空白字符,包括空格、制表符、换行符等。以下是使用示例:
```python
my_string = " Hello, World! "
cleaned_string = my_string.strip()
print(cleaned_string) # 输出: "Hello, World!"
```
如果你只想去掉左侧或右侧的空格,可以用`lstrip()`(左移除)或`rstrip()`(右移除)代替:
```python
left_spaces_string = " Hello, World! "
right_spaces_string = "Hello, World! "
left_cleaned = left_spaces_string.lstrip()
right_cleaned = right_spaces_string.rstrip()
print(left_cleaned) # 输出: "Hello, World! "
print(right_cleaned) # 输出: " Hello, World!"
```
阅读全文