Python 字串的有趣事實
在本文中,我們將瞭解有關 Python 3.x 中字串的一些有趣的事實。或更早版本。
- 不可變性
- 自動檢測轉義序列
- 直接切片
- 索引訪問
不可變性
這意味著 <string> 型別無法進行修改,我們只能讀取字串內容。
示例
inp = 'Tutorials point' # output print(inp) # assigning a new value to a particular index in a string inp[0] = 't' print(inp) # raises an error
輸出
TypeError: 'str' object does not support item assignment
自動檢測轉義序列
包含反斜槓的字串會自動檢測為轉義序列。
示例
inp = 'Tutorials point' # output print(inp+”\n”+”101”)
輸出
Tutorials point 101
直接切片
我們都知道 c 或 c++ 中的子字串方法,切片在 Python 中執行相同的操作。它需要兩個強制引數和 1 個可選引數。強制引數為開始索引(包括)和結束索引(不包括)可選引數為步長,即遞增或遞減值。預設值為 1。
示例
inp = 'Tutorials point' # output print(inp[0:5])
輸出
Tutor
索引訪問
由於所有元素都儲存在連續的格式中,因此我們可以藉助索引直接訪問元素。
示例
inp = 'Tutorials point' # output print(inp[0]+inp[1])
輸出
Tu
結論
在本文中,我們瞭解了有關 Python 3.x 中字串的一些有趣的事實。或更早版本。
廣告