python字符串去除空格
时间: 2023-09-04 22:15:39 浏览: 49
在 Python 中,可以使用字符串的 `strip()` 方法来去除字符串两端的空格,即:
```python
s = " hello world "
s = s.strip()
print(s) # 输出:hello world
```
如果要只去除左边或右边的空格,可以使用 `lstrip()` 或 `rstrip()` 方法,分别表示去除左边和右边的空格。例如:
```python
s = " hello world "
s = s.lstrip()
print(s) # 输出:hello world
s = " hello world "
s = s.rstrip()
print(s) # 输出: hello world
```
另外,如果要去除字符串中间的空格,可以使用 `replace()` 方法,将空格替换为空字符串即可,例如:
```python
s = "he llo w or ld"
s = s.replace(" ", "")
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()` 方法,它会去除字符串两端的空格,但不会去除字符串中间的空格。