用python的re去空格
时间: 2024-01-26 22:40:28 浏览: 20
可以使用 Python 中的 re 模块来去除字符串中的空格。具体的方法如下:
```python
import re
# 定义一个字符串
str = ' hello world '
# 使用 re.sub() 方法去除空格
result = re.sub(r'\s+', '', str)
print(result) # 输出:helloworld
```
在上面的代码中,我们首先导入了 re 模块,然后定义了一个包含空格的字符串。接着,我们使用 re.sub() 方法来替换字符串中的空格,其中 r'\s+' 用于匹配一个或多个空格。最后,打印结果即可。
注意:该方法会将字符串中所有的空格都去除掉,包括行末和行首的空格。如果只想去除字符串两端的空格,可以使用字符串的 strip() 方法。
相关问题
python re 空格
使用 Python re 模块匹配空格可以使用空格字符的特殊转义符 \s。例如,可以使用以下代码匹配一个字符串中的所有空格:
```
import re
text = "This is a string with spaces."
spaces = re.findall(r'\s', text)
print(spaces)
```
输出结果为:
```
[' ', ' ', ' ', ' ']
```
上述代码使用 re.findall() 方法查找字符串中的所有空格,并将它们存储在一个列表中。
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()` 方法只去除字符串开头和结尾的空格,而不会去除字符串中间的空格。