Python中去除字符串中的所有空格
时间: 2023-05-21 20:01:18 浏览: 97
可以使用字符串的 replace() 方法,将空格替换为空字符串即可。示例代码如下:
```
s = "hello world"
s = s.replace(" ", "")
print(s) # 输出"helloworld"
```
相关问题
用python 去除字符串中所有的空格
可以使用字符串的 `replace()` 方法来去除字符串中的空格,将空格替换为空字符串即可。示例代码如下:
```python
s = "Hello World! "
s = s.replace(" ", "") # 将空格替换为空字符串
print(s) # 输出结果为 "HelloWorld!"
```
另外,如果希望去除字符串两端的空格,可以使用字符串的 `strip()` 方法。示例代码如下:
```python
s = " Hello World! "
s = s.strip() # 去除两端空格
print(s) # 输出结果为 "Hello World!"
```
python,去除字符串中的空格
可以使用字符串对象的 `replace()` 方法来替换空格,或者使用字符串对象的 `strip()` 方法来去除字符串首尾的空格。
例如:
```python
s = " This is a string with spaces. "
s = s.replace(" ", "") # 替换空格
print(s) # 输出:Thisisastringwithspaces.
s = " This is a string with spaces. "
s = s.strip() # 去除首尾空格
print(s) # 输出:This is a string with spaces.
```
需要注意的是,`strip()` 方法只能去除字符串首尾的空格,而不能去除字符串中间的空格。如果需要去除字符串中间的空格,可以使用 `replace()` 方法。