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('測試成功!')

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM