个人的解法,稍微有点复杂,但是逻辑很清晰,请看以下代码。
def trim(s):
if s=='' or s==' ':
res = s
else:
s_revese = s[::-1]
for i in range(len(s)):
if s[i]!=' ':
break
for j in range(len(s)):
if s_revese[j]!=' ':
break
index = len(s)-j
res = s[i:index]
return res
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('测试成功!')
参考:
https://www.liaoxuefeng.com/wiki/1016959663602400/1017269965565856
https://blog.youkuaiyun.com/daniel960601/article/details/79174915
本文提供了一个用于去除字符串两端空白字符的Python函数实现。该函数通过逆序遍历来确定字符串的有效范围,从而达到去除首尾空白字符的目的。文章还包含了一些测试用例以验证函数的正确性。
1704

被折叠的 条评论
为什么被折叠?



