利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法。 程序与运行结果拍照上传
时间: 2024-05-02 10:19:16 浏览: 14
代码如下:
```python
def trim(s):
while s[:1] == ' ':
s = s[1:]
while s[-1:] == ' ':
s = s[:-1]
return s
```
测试代码如下:
```python
print(trim(' hello world '))
```
运行结果如下:
```
hello world
```
相关问题
利用切片操作,实现一个 trim(函数,去除宇符串首尾的空 格,注意不要调用 str 的strip0方法:
好的,这个问题可以用 Python 代码来解决。代码如下:
```python
def trim(s):
if len(s) == 0: # 如果字符串为空,则直接返回
return s
start = 0 # 去除头部空格
while start < len(s) and s[start] == ' ':
start += 1
end = len(s) - 1 # 去除尾部空格
while end >= 0 and s[end] == ' ':
end -= 1
return s[start:end+1]
```
这里我们定义了一个名为 trim 的函数,它接收一个字符串 s 作为输入,并返回去除了首尾空格之后的字符串。我们使用了两个 while 循环来去除头部和尾部的空格。在第一个循环中,我们从字符串的第一个字符开始遍历,直到找到第一个不是空格的字符为止。在第二个循环中,我们从字符串的最后一个字符开始遍历,直到找到第一个不是空格的字符为止。
这里我们并没有使用 str 的 strip 方法,而是利用了切片操作来返回去除了首尾空格之后的字符串。
请实现trim函数 去掉字符串头尾的空格
好的,以下是一个简单的实现:
```python
def trim(s):
if len(s) == 0:
return s
start = 0
end = len(s) - 1
while start < len(s) and s[start] == ' ':
start += 1
while end >= 0 and s[end] == ' ':
end -= 1
if start > end:
return ''
return s[start:end+1]
```
这个函数首先检查字符串是否为空,如果是,则直接返回原字符串。然后从字符串的开头和结尾开始遍历,找到第一个非空格字符和最后一个非空格字符的位置。最后返回这个新的字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)