Python去处字符串中间的空格
时间: 2023-07-03 22:21:41 浏览: 73
可以使用字符串的 `replace()` 方法去除字符串中间的空格,例如:
```python
s = "hello world"
s = s.replace(" ", "")
print(s) # 输出:helloworld
```
这里的 `replace()` 方法用于将字符串中的空格替换为空字符串,从而实现去除空格的效果。如果字符串中的空格不止一个,也可以一次性替换掉多个空格,例如:
```python
s = "hello world"
s = s.replace(" ", "")
print(s) # 输出:helloworld
```
这里将字符串中的所有空格都替换为空字符串,从而得到去除空格的结果。
相关问题
python判断字符串中空格数量
可以使用 Python 内置函数 `count()` 来判断字符串中空格的数量,示例如下:
```python
s = "hello world"
count = s.count(" ")
print(count)
```
输出结果为:
```
1
```
其中 `count()` 函数的参数是待查找的子字符串,返回值是子字符串在原字符串中出现的次数。因此,以上代码中 `count` 的值就是字符串 `s` 中空格的数量。
python中字符串消除空格
在Python中,可以使用strip()方法来消除字符串两端的空格,也可以使用replace()方法来替换字符串中的空格。例如:
```python
s = " hello world! "
s = s.strip() # 消除两端空格
print(s) # 输出 "hello world!"
s = " hello world! "
s = s.replace(" ", "") # 替换空格
print(s) # 输出 "helloworld!"
```
需要注意的是,以上两种方法都不会改变原始字符串的值,而是返回一个新的字符串。如果想要在原始字符串上进行修改,则需要重新赋值。