1. 程式人生 > >如何截取字符串?

如何截取字符串?

-s font 字符 ria -1 索引 intro world python

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

如何截取字符串?