首页 > 编程语言 > 详细

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

时间:2019-10-29 15:34:17      阅读:83      评论:0      收藏:0      [点我收藏+]

方法一:

# -*- 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(‘测试成功!‘)

  

 

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

原文:https://www.cnblogs.com/chling/p/11758075.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!