Python 字符串切片
字符串切片
- 首先字符串的 strip() 方法可以去掉字符串的首尾空白字符;
- 字典、元组、以及字符串都可以进行切片,索引从0开始,s[0] 表示切片后的第一个元素,s[-1] 表示最后一个元素;
- 如果是空字符,不存在切片,所以 ‘’[0] 会报错(IndexError: string index out of range);
自定义函数去掉字符串的首尾空白字符:
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
def trim(s):
if len(s) != 0:
while s[:1] == ' ':
s = s[1:]
while s[-1:] == ' ':
s = s[:-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('测试成功!')
使用递归:
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
def trim(s):
if s == '':
return s
elif s[0] == ' ':
s = trim(s[1:])
elif s[-1] == ' ':
s = trim(s[:-1])
return s
还没有评论,来说两句吧...