第五章 列表、元组和字符串[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 都可以使用在元组上。

猜你喜欢

转载自www.cnblogs.com/daodantou/p/10221908.html