首页 > 技术文章 > 如何截取字符串?

llxx07 2017-05-10 15:14 原文

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

推荐阅读