Python学习笔记--字符串切片


Day 1 :切片操作

  Q:利用切片操作,实现一个函数trim(),去除字符串首尾的空格

  思路:

  通用方法:罗列所有处理数据-->每种数据的处理方法-->归类方法并选择合适的判断循环语句-->测试所有组合的Testcase;

  首先明确对于空格场景,所有字符串的形式和对应处理方法:

  1、空字符串:[],通过if匹配,直接返回字符串本身;

  2、首尾无空格:通过if匹配,直接返回字符串本身;

  3、段首有空格:通过if匹配,a、统计段首所有空格数,返回切片值;b、逐一切片,利用迭代返回最终的切片值;

  4、段尾有空格:通过else匹配,a、统计段尾所有空格数,返回切片值;b、逐一切片,利用迭代返回最终的切片值;

  5、首尾均有空格:先匹配3,然后匹配4,即可得到结果;

 

  a、方法在匹配'          '场景时,无合适方法,代码结构复杂度高,不考虑

 

  判断循环语句结构:

  def trim(s):

    if (s == " " or ( s[0] != " " and s[-1] != " " )):                             #匹配1、2场景;

    elif (s[0] == " "):                                                                        #匹配3、5场景;

    else(s[-1] == " "):                                                                       #匹配4、5场景;

  处理方法:

    return s                                                                                      #匹配1、2场景;

    return trim(s[1:])                                                                       #匹配3、5场景,利用迭代,逐一切片;

    return trim(s[:-1])                                                                      #匹配4、5场景,利用迭代,逐一切片

 

  Testcase:

    1、''               

    2、'hello'

    3、'            hello'

    4、'hello            '

    5、'      hello      '

 

  最终code:

  

def trim(s):

  if(len(s) == 0 or (s[0] != ' ' and s[-1] != ' ')): 
    return s
  elif s[0] == ' ':
    return trim(s[1:])
  else:
    return trim(s[:-1])

if __name__ == '__main__':
  if trim('hello ') != 'hello':
    test = trim('hello ')
    print test,'a'
    print('测试失败!')
  elif trim(' hello') != 'hello':
    test = trim(' hello')
    print test,'b'
    print('测试失败!')
  elif trim(' hello ') != 'hello':
    test = trim(' hello ')
    print test,'c'
    print('测试失败!')
  elif trim('') != '':
    test = trim('')
    print test,'d'
    print('测试失败!')
  elif trim(' ') != '':
    test = trim(' ')
    print test,'e'
    print('测试失败!')
  else:
    print('测试成功!')
  pass

 

    

    

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM