1. 程式人生 > >第五章 列表、元組和字串[DDT書本學習 小甲魚]【5】

第五章 列表、元組和字串[DDT書本學習 小甲魚]【5】

5.2.2 更新和刪除元組
含蓄做法:拷貝原始元組構建新的元組貼上標籤
程式碼 新增元素
temp=("小雞","小鴨","小豬")
temp=temp(:2)+("小猴",)+temp(2:)
print(temp)
-------------------------------
('小雞', '小鴨', '小猴', '小豬')

程式碼 刪除元素
temp=("小雞","小鴨","小猴","小豬")
temp=temp[:2]+temp[3:]
print(temp)
---------------------------------
('小雞', '小鴨', '小豬')

程式碼 刪除元組
temp=("小雞","小鴨","小豬")
del temp
print(temp)
------------------------------
Traceback (most recent call last):
File "C:/Users/Daodantou/PycharmProjects/s14/day6/h2.py", line 3, in <module>
print(temp)
NameError: name 'temp' is not defined #元組已經不存在,所以報錯。

日常很少用del去刪除整個元組,因為Python的回收機制在陣列不再用時自動刪除。
關係操作符、邏輯操作符、成員操作符in 和not in 都可以使用在元組上。
5.3 字串
字串中分片的概念 Python中沒有字串和字元之分!!!
程式碼
str1="I Love You"
print(str1[:6])
print(str2[0])
----------------
I Love
I

另外,字串和元組一樣,都是“一言既出,駟馬難追”的傢伙。一旦定下來就不能修改,
必須要改就只能委曲求全,曲線救國了。
str1="I Love You"
str1=str1[:6]+" he and "+str1[7:]
print(str1)
---------------------------------
I Love he and You
關係比較操作符、邏輯操作符、成員操作符in 和not in 都可以使用在元組上。