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('测试成功!')
    

      

  • 相关阅读:
    内置函数,闭包。装饰器初识
    生成器
    百度ai 接口调用
    迭代器
    HashMap与ConcurrentHashMap的测试报告
    ConcurrentHashMap原理分析
    centos 5.3 安装(samba 3.4.4)
    什么是shell? bash和shell有什么关系?
    Linux中使用export命令设置环境变量
    profile bashrc bash_profile之间的区别和联系
  • 原文地址:https://www.cnblogs.com/chling/p/11758075.html
Copyright © 2011-2022 走看看