首页 > 代码库 > 如何截取字符串?
如何截取字符串?
1、索引(可以用于获取一个子字符串)
正索引(从左往右计数,第一个字符为0开始)
word=‘hello world’
print word[0]
结果:h
负索引(从右往左计数,最后一个字符-1开始)
word=‘hello world’
print word[-1]
结果:d
2、切片(用以获取字符串中多个连接的子字符)
word=‘hello world’
print word[1:4]
结果:ello
切片索引的默认值(省略的第一个索引默认为零,省略的第二个索引默认为切片的字符串的大小。)
word=‘hello world’
Print word[:2]
结果:hel
word=‘hello world’
Print word[2:]
结果:lo world
print word[:2]+word[2:]
结果:hello world
参考资料:http://python.usyiyi.cn/translate/python_278/tutorial/introduction.html
如何截取字符串?
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。