python 中去除空格的方法 以及 ''.join(list) 的用法


python 中去除空格的方法

def trim(s):
    l=[]
    for i in s:
        if i!=' ':
            l.append(i)
    return ''.join(l)

其中可以使用下面的

''.join(list) 

','.join(list) 

 

python 去除首尾空格的方法

def trim(s):
    while len(s)!=0:
        if s[0]==' ':
            s=s[1:]
        elif s[-1]==' ':
            s=s[:-1] else:
            break
    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('測試成功!')

運行過代碼沒有問題

 


免責聲明!

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



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