python列表、元组、字符串

python列表、元组、字符串


python中列表、元组、字符串均为可迭代对象:

lst = [1,2,3,4]
for i in lst:print(i,end=' ')
print()
tu  = (1,2,3,4)
for i in tu:print(i,end=' ')
print()
str = '1234'
for i in str:print(i,end=' ')
print()
1 2 3 4 
1 2 3 4 
1 2 3 4 

python中的列表为可修改对象,对列表的大多数操作可以在原列表上直接进行。列表底层为包含对象引用数组长度数组首地址的结构体,因而改变列表的长度并不销毁列表对象。

lst = []
print(f'id of lst is : {id(lst)} ;lst : {lst}')
lst.append('a')
print(f'id of lst is : {id(lst)} ;lst : {lst}')
id of lst is : 1787675887304 ;lst : []
id of lst is : 1787675887304 ;lst : ['a']

python中的tuple、string均为不可修改对象。所有修改string值的操作均会返回新的对象,原对象不变;无法通过下标修改tuple和string

str = 'abcde'
print(f'id of str : {id(str)} ;str : {str}')
str1=str.capitalize()
print(f'id of str1: {id(str1)} ;str1: {str1}')
print(f'id of str : {id(str)} ;str : {str}')
id of str : 2461927781688 ;str : abcde
id of str1: 2461930351840 ;str1: Abcde
id of str : 2461927781688 ;str : abcde
tu = (1,2,3)
tu[1]=5
Traceback (most recent call last):
  File "C:/PycharmProjects/practice.py", line 253, in <module>
    tu[1]=5
TypeError: 'tuple' object does not support item assignment
发布了4 篇原创文章 · 获赞 3 · 访问量 770

猜你喜欢

转载自blog.csdn.net/weixin_39630484/article/details/85629378