Discuss / Python / 来交作业了

来交作业了

Topic source
# -*- coding: utf-8 -*-
def trim(s):
    head = 0    
    tail = len(s)
    # 若字符串为空,输出原字符串    
    if len(s) == 0:
        return s
    # 检查首部的空格    
    while (s[head] == ' ') and (head < len(s)):
        head = head+1        
        # 若字符串全为空格则输出''
        if head == len(s):
            return ''
    # 检查末尾的空格    
    while (s[tail-1] == ' ') and (tail > 0):
        tail = tail-1    return s[head:tail]


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

清晰明了

TomYazawa

#3 Created at ... [Delete] [Delete and Lock User]

写得真好


  • 1

Reply