切片操作在Python中應用十分廣泛并不局限于字元串操作,在清單等資料結構上同樣适用十分重要。
Python字元串
與許多常見的程式設計語言不同,Python中字元串可以用
單引号
引起來,也可以用
雙引号
引起來。
s = "Hello Python"
t = 'Hello world'
Python字元串的下标也是從0開始的。但可以從末尾往前引用,此時下标從-1開始。例如下列代碼:
t = 'Hello world'
print(t[-1])
輸出:
d
字元串切片
切片格式
s[start:end]
,注意實際上切片範圍是左閉右開的
[start,end)
,如果沒有start或end會預設補充此方向上的
起點
和
終點
。
代碼:
s = "Hello Python,hello world"
# 注意左閉右開
print(s[6:12])
# 補充0為start
print(s[:12])
# 補充24 + 1為end(由于左閉右開要+1)
print(s[6:])
# 補充開始和結尾 相當于輸出整串
print(s[:])
測試輸出:
Python
Hello Python
Python,hello world
Hello Python,hello world
帶有方向和步長的字元串切片
此時切片格式
s[start:end:step]
。step表示在[start:end)範圍内每step個字元截取一個字元。
例如:
s = "abcdefghij"
print(s[::2])
輸出:
acegi
當step為負值時,表示反向切片,如果沒有start或end會預設補充此方向上的起點和終點。
s = "abcdefghij"
# 反向切片
print(s[9:0:-1])
# 反向步長絕對值不為1
print(s[9:0:-3])
輸出:
jihgfedcb
jgd
在帶有方向的切片時start和end必須合法否則什麼也切不出來:
例如下方代碼得不到任何輸出
s = "abcdefghij"
# 反向切片
print(s[9:0:1])
# 反向帶步長
print(s[0:9:-1])
輸出:
(空)
留下一個reverse(反向輸出字元串)代碼做思考:
print(s[::-1])