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