python去除左右空格
时间: 2023-05-29 21:03:10 浏览: 97
可以使用字符串的strip()方法去除左右空格。
示例代码:
```python
s = ' hello world '
s = s.strip()
print(s) # 输出:'hello world'
```
strip()方法默认去除字符串左右两端的空格,也可以指定去除其他字符,例如:
```python
s = '***hello world***'
s = s.strip('*')
print(s) # 输出:'hello world'
```
相关问题
python去除前后空格
在Python中,可以使用三种方法来去除字符串的前后空格。第一种方法是使用rstrip()函数,它可以去除字符串末尾的空格。例如,如果我们有一个字符串favorite_language=' Python ',我们可以使用favorite_language.rstrip()来去除末尾的空格。[1]
第二种方法是使用lstrip()函数,它可以去除字符串开头的空格。例如,如果我们有一个字符串string = " * it is blank space test * ",我们可以使用string.lstrip()来去除开头的空格。[2]
第三种方法是使用strip()函数,它可以同时去除字符串的前后空格。例如,如果我们有一个字符串string = " *it is blank space test * ",我们可以使用string.strip()来去除前后的空格。[3]
python去除字符空格
要去除字符串中的空格,可以使用字符串的 `replace()` 方法或者使用正则表达式。
1. 使用 `replace()` 方法:
```python
my_string = " hello world "
new_string = my_string.replace(" ", "")
print(new_string)
```
输出:
```
helloworld
```
在这个例子中,我们使用 `replace(" ", "")` 将字符串中的空格替换为空字符串。
2. 使用正则表达式:
```python
import re
my_string = " hello world "
new_string = re.sub(r"\s+", "", my_string)
print(new_string)
```
输出:
```
helloworld
```
在这个例子中,我们使用 `re.sub()` 函数和正则表达式 `\s+` 来匹配一个或多个连续的空格,并将其替换为空字符串。
无论使用哪种方法,都会去除字符串中的所有空格。如果你只想去除字符串开头和结尾的空格,可以使用 `strip()` 方法:
```python
my_string = " hello world "
new_string = my_string.strip()
print(new_string)
```
输出:
```
hello world
```
`strip()` 方法只去除字符串开头和结尾的空格,而不会去除字符串中间的空格。