python字符串去除空格
时间: 2023-07-24 21:06:38 浏览: 55
可以使用 `strip()` 方法去除字符串两端的空格,也可以使用 `replace()` 方法将字符串中的空格替换为空字符。例如:
```python
s = ' hello world '
s = s.strip() # 去除两端空格
print(s) # 输出:'hello world'
s = ' hello world '
s = s.replace(' ', '') # 将空格替换为空字符
print(s) # 输出:'helloworld'
```
如果你想去除字符串中所有空格,而不仅仅是两端的空格,可以使用正则表达式来实现:
```python
import re
s = ' hello world '
s = re.sub(r'\s+', '', s) # 将所有空格替换为空字符
print(s) # 输出:'helloworld'
```
相关问题
python字符串切片空格
你可以使用字符串的切片操作来去除字符串中的空格。切片操作可以通过指定起始位置和结束位置来截取字符串的一部分。在这种情况下,你可以使用字符串的 `replace()` 方法将空格替换为空字符串,然后再进行切片操作。下面是一个示例:
```python
string = "Python 字符串 切片 空格"
string = string.replace(" ", "") # 替换空格为空字符串
sliced_string = string[1:4] # 进行切片操作
print(sliced_string) # 输出:yth
```
在上面的示例中,我们首先使用 `replace()` 方法将空格替换为空字符串,得到新的字符串 "Python字符串切片空格"。然后,我们使用切片操作 `string[1:4]` 来获取索引位置从1到3的子字符串,即 "yth"。
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()` 方法,它会去除字符串两端的空格,但不会去除字符串中间的空格。