zoukankan      html  css  js  c++  java
  • 利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:

    首先判断字符串的长度是否为0,如果是,直接返回字符串

    第二,循环判断字符串的首部是否有空格,如果有,去掉空格,再判断字符串的长度是否为0,如果是,直接返回字符串

    第三,循环判断字符串的尾部是否有空格,如果有,去掉空格,再判断字符串的长度是否为0,如果是,直接返回字符串

    最后,返回字符串

     1 # -*- coding: utf-8 -*-
     2 def trim(s):
     3     if 0==len(s):
     4         return s
     5         
     6     while ' '==s[0]:
     7         s=s[1:]
     8         if 0==len(s):
     9             return s
    10             
    11     while ' '==s[-1]:
    12         s=s[:-1]
    13         if 0==len(s):
    14             return s
    15             
    16     return s

    测试代码:

     1 # 测试:
     2 from trim import trim
     3 if trim('hello  ') != 'hello':
     4     print('测试失败!')
     5 elif trim('  hello') != 'hello':
     6     print('测试失败!')
     7 elif trim('  hello  ') != 'hello':
     8     print('测试失败!')
     9 elif trim('  hello  world  ') != 'hello  world':
    10     print('测试失败!')
    11 elif trim('') != '':
    12     print('测试失败!')
    13 elif trim('    ') != '':
    14     print('测试失败!')
    15 else:
    16     print('测试成功!')
  • 相关阅读:
    【中山纪念中学六年级模拟赛】方格翻转 题解
    高斯消元
    net 控件开发资料
    使用自定义验证组件库扩展 Windows 窗体
    POJ 3032
    UVa 10878 Decode the tape
    C语言I博客作业03
    第十周助教总结
    第十二周助教总结
    C语言I博客作业06
  • 原文地址:https://www.cnblogs.com/denggelin/p/8953629.html
Copyright © 2011-2022 走看看