栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python-基础知识3-切片

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python-基础知识3-切片

zifuchuang
0123456789
-10-9-8-7-6-5-4-3-2-1

s[0:3]='zif'             #表示从索引0开始取,直到索引3为止,但不包括索引3

s[:3]=s[0:3]=s[0]、s[1]、s[2] #前面的默认为0,

s[-3:-1]=s[-3]、s[-2]               

利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:

# -*- coding: utf-8 -*-
def trim(s):
    if(len(s)==0):    #学会考虑极端情况
        return s
    if s[0]==' ':
        return trim(s[1:])
    if s[-1]==' ':
        return trim(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('测试成功!')

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/357455.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号