1. 使用 `strip()` 方法去除字符串开头和结尾的空格。
```python
my_string = " Example with spaces "
stripped_string = my_string.strip()
print(stripped_string) 输出: "Example with spaces"
2. 使用 `replace()` 方法将字符串中的所有空格替换为空字符串。
```python
my_string = " Example with spaces "
stripped_string = my_string.replace(" ", "")
print(stripped_string) 输出: "Examplewithspaces"
3. 使用正则表达式 `re.sub()` 方法匹配和替换所有空格。
```python
import re
my_string = " Example with spaces "
stripped_string = re.sub(r" ", "", my_string)
print(stripped_string) 输出: "Examplewithspaces"
4. 使用 `split()` 和 `join()` 方法去除字符串中的所有空格。
```python
my_string = " Example with spaces "
stripped_string = "".join(my_string.split())
print(stripped_string) 输出: "Examplewithspaces"
5. 使用 `lstrip()` 和 `rstrip()` 方法分别去除字符串开头和结尾的空格。
```python
my_string = " Example with spaces "
stripped_string = my_string.lstrip()
print(stripped_string) 输出: "Example with spaces"
选择哪种方法取决于你的具体需求。通常情况下,`strip()` 方法是最简单快捷的选择