python字符串中如何去除空格
时间: 2023-12-13 07:02:39 浏览: 28
可以使用字符串的 `strip()` 方法去除字符串中的空格,该方法会去除字符串开头和结尾的空格。例如:
```python
s = " hello world "
s = s.strip()
print(s) # 输出:hello world
```
如果要去除字符串中间的空格,可以使用字符串的 `replace()` 方法,将空格替换为空字符串即可。例如:
```python
s = "hello world"
s = s.replace(" ", "")
print(s) # 输出:helloworld
```
另外,如果要去除特定位置的空格,可以使用字符串的切片操作,将需要去除的空格从字符串中切掉。例如:
```python
s = "hello world"
s = s[:5] + s[10:]
print(s) # 输出:hello world
```
相关问题
Python字符串中去除空格
可以使用 `replace()` 方法将字符串中的空格替换成空字符串:
```python
text = " Hello World! "
clean_text = text.replace(" ", "")
print(clean_text)
```
输出结果为:
```
HelloWorld!
```
这里将空格替换成空字符串,实现了去除空格的效果。如果你想只去除字符串两端的空格,可以使用 `strip()` 方法:
```python
text = " Hello World! "
clean_text = text.strip()
print(clean_text)
```
输出结果为:
```
Hello World!
```
这里使用了 `strip()` 方法,它会去除字符串两端的空格,但不会去除字符串中间的空格。
python去除字符串中的空格
可以使用字符串的replace()函数或者正则表达式来去除字符串中的空格。下面是使用replace()函数去除空格的方法:
```python
str = " hello world "
new_str = str.replace(" ", "")
print(new_str) # 输出"helloworld"
```
下面是使用正则表达式去除空格的方法:
```python
import re
str = " hello world "
new_str = re.sub(r"\s+", "", str)
print(new_str) # 输出"helloworld"
```
两种方法都可以去除字符串中的空格,具体使用哪种方法取决于实际需求。