python每日一练:利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法

本文内容皆为作者原创,码字不易,如需转载,请注明出处:https://www.cnblogs.com/temari/p/13411894.html

最近在跟着廖雪峰老师的官方网站学习python,廖老师的教程讲解的很细致,每章课后会布置一道练习题,用于巩固本章学习的知识点,因此想到使用博客记录下每次练习的作业,也是对自己学习成果的检测。

一,本次章节学习内容:

切片

二,本章课后作业:

题目:利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法

三,作业代码实现
# -*- coding: utf-8 -*-
def trim(s):
    t=""
#去掉首空格
    for i in range(len(s)):
        if s[i] !=' ':
            t=s[i:]
            break
#去掉末尾空格:判断字符串的长度,如果长度为0,不予操作,如果大于0,循环判断列表的末尾是否为空格,是则删除空格,直到末尾无空格,跳出循环
    if len(t)>0:
         while (t[-1] == ' '):
                t= t[:-1]
    print("尾空格去除:"+t+"|")
    return t
# 测试:
if trim('hello  ') != 'hello':
    print('1测试失败!')
elif trim('  hello') != 'hello':
    print('2测试失败!')
elif trim('  hello  ') != 'hello':
    print('3测试失败!')
elif trim('  hello  world  ') != 'hello  world':
    print('4测试失败!')
elif trim('') != '':
    print('5测试失败!')
elif trim('    ') != '':
    print('6测试失败!')
else:
    print('测试成功!')
四,代码演示

原文地址:https://www.cnblogs.com/temari/p/13411894.html