当前位置: 代码迷 >> 综合 >> 去除字符串的首尾空格 Python实现
  详细解决方案

去除字符串的首尾空格 Python实现

热度:74   发布时间:2024-02-13 05:28:53.0

学习资源:廖雪峰Python教程——切片

牢记:代码越少越好,逻辑越简单越好

尝试了3种实现方法,其中trim1是类C的实现,逻辑复杂,trim2和trim都是pythonic的,但是trim巧妙地解决了空字符串地情况,代码更加少、更加简洁。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-def trim1(s):idx=-1for ss in s:      #去除首部空格if(ss==' '):idx += 1    #最后一个空格所在的下标else:s=s[idx+1:]breakridx=0count=0for ss in s:if(ss==' '):count += 1continueelse:ridx += 1+count    #最后一个非空格字符的下一个下标count=0s=s[:ridx]return sdef trim2(s):while((s != '') and (s[0]==' ')):s=s[1:]while(s != '' and s[-1]==' '):s=s[:-1]return sdef trim(s):while(s[:1]==' '):    #即使空字符串也不会索引越界s=s[1:]while(s[-1:]==' '):    #即使空字符串也不会索引越界s=s[:-1]return s#test
print("trim('hello  ')          =", trim('hello  ')         )
print("trim('  hello')          =", trim('  hello')         )
print("trim('  hello  ')        =", trim('  hello  ')       )
print("trim('  hello  world  ') =", trim('  hello  world  '))
print("trim('')                 =", trim('')                )
print("trim('    ')             =", trim('    ')            )if trim('hello  ') != 'hello':print('#1 测试失败!')
elif trim('  hello') != 'hello':print('#2 测试失败!')
elif trim('  hello  ') != 'hello':print('#3 测试失败!')
elif trim('  hello  world  ') != 'hello  world':print('#4 测试失败!')
elif trim('') != '':print('#5 测试失败!')
elif trim('    ') != '':print('#6 测试失败!')
else:print('测试成功!')

测试结果:

C:\python>trim.py
trim('hello  ')          = hello
trim('  hello')          = hello
trim('  hello  ')        = hello
trim('  hello  world  ') = hello  world
trim('')                 =
trim('    ')             =
测试成功!

  相关解决方案