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

    方法一:

    # -*- coding: utf-8 -*-
    
    # 利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:
    
    def trim(s):
        while s[:1] == ' ':
            s = s[1:]
        while s[-1:] == ' ':
            s = s[0:-1]
        return s
    
    # 测试:
    if trim('hello  ') != 'hello':
        print('测试失败!')
    elif trim('  hello') != 'hello':
        print('测试失败!')
    elif trim('  hello  ') != 'hello':
        print('测试失败!')
    elif trim('  hello  world  ') != 'hello  world':
        print('测试失败!')
    elif trim('') != '':
        print('测试失败!')
    elif trim('    ') != '':
        print('测试失败!')
    else:
        print('测试成功!')
    

      

    方法二:

    (此方法会有一个问题,当字符串仅仅是一个空格时‘ ’,会返回return s[1:0];虽然不会报错,但是会比较奇怪。测试了下,当s=‘abc’时,s[1:0]=‘’ 空值)

    # -*- coding: utf-8 -*-
    
    def trim(s):
        i = 0
        j = len(s) - 1
        while i < len(s):
            if s[i] == ' ':
                i = i + 1
            else:
                break
        while j > -1:
            if s[j] == ' ':
                j = j - 1
            else:
                break
        return s[i:j+1]
    
    # 测试:
    if trim('hello  ') != 'hello':
        print('测试失败!')
    elif trim('  hello') != 'hello':
        print('测试失败!')
    elif trim('  hello  ') != 'hello':
        print('测试失败!')
    elif trim('  hello  world  ') != 'hello  world':
        print('测试失败!')
    elif trim('') != '':
        print('测试失败!')
    elif trim('    ') != '':
        print('测试失败!')
    else:
        print('测试成功!')
    

      

  • 相关阅读:
    iOS 字体
    接口继承和实现继承的区别
    实验楼实验——LINUX基础入门
    试看看能不能发布
    mysql binlog恢复
    percona
    ssh2 php扩展
    sphinx
    ngios
    socketlog
  • 原文地址:https://www.cnblogs.com/chling/p/11758075.html
Copyright © 2011-2022 走看看