python去除字符空格
时间: 2023-07-17 11:07:31 浏览: 45
要去除字符串中的空格,可以使用字符串的 `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()` 方法只去除字符串开头和结尾的空格,而不会去除字符串中间的空格。
相关问题
python去除字符串空格
您好,关于python去除字符串空格,您可以使用strip()函数来实现,具体方法为:
str.strip():去除字符串两端的空格
str.lstrip():去除字符串左侧的空格
str.rstrip():去除字符串右侧的空格
示例代码如下:
``` python
s = " hello world "
s.strip() # 去除两端空格,输出:'hello world'
s.lstrip() # 去除左空格,输出:'hello world '
s.rstrip() # 去除右空格,输出:' hello world'
```
希望对您有所帮助。
python 去除字符串空格
可以使用字符串的 `strip()` 方法去除字符串开头和结尾的空格,也可以使用 `replace()` 方法去除字符串中所有的空格。示例如下:
```python
# 使用 strip() 方法去除开头和结尾的空格
s = ' hello world '
s = s.strip()
print(s) # 输出:'hello world'
# 使用 replace() 方法去除所有空格
s = ' hello world '
s = s.replace(' ', '')
print(s) # 输出:'helloworld'
```
需要注意的是,`strip()` 和 `replace()` 方法都返回新的字符串,原字符串并没有被修改。如果要修改原字符串,需要将修改后的字符串赋值给原字符串。