用Python写请将字符串string两侧空格去除
时间: 2023-04-01 19:03:14 浏览: 152
可以使用Python内置的strip()函数来去除字符串两侧的空格,示例代码如下:
string = " hello world "
string = string.strip()
print(string)
输出结果为:hello world
相关问题
python去除字符串两侧的空格
可以使用字符串的`strip()`方法去除字符串两侧的空格,例如:
```
string = " hello world "
new_string = string.strip()
print(new_string) # 输出:hello world
```
此外,如果只需要去除字符串左侧或右侧的空格,可以使用`lstrip()`和`rstrip()`方法,分别表示去除左侧和右侧的空格。例如:
```
string = " hello world "
new_string = string.lstrip()
print(new_string) # 输出:hello world
new_string = string.rstrip()
print(new_string) # 输出: hello world
```
python 将字符串中间的空格去掉
可以使用 Python 中的 replace() 函数将字符串中的空格去掉,例如:
```python
string = "hello world"
new_string = string.replace(" ", "")
print(new_string)
```
输出结果为:
```
helloworld
```