相同点
都属于序列类型的数据
所谓序列类型的数据,就是说它的每一个元素都可以通过指定一个编号,行话叫做“偏移量”的方式得到,而要想一次得到多个元素,可以使用切片。偏移量从0开始,总元素数减1结束。
例如:
>>> welcome_str = "Welcome you">>> welcome_str[0]'W'>>> welcome_str[1]'e'>>> welcome_str[len(welcome_str)-1]'u'>>> welcome_str[:4]'Welc'>>> a = "python">>> a*3'pythonpythonpython'>>> git_list = ["qiwsir","github","io"]>>> git_list[0]'qiwsir'>>> git_list[len(git_list)-1]'io'>>> git_list[0:2]['qiwsir', 'github']>>> b = ['qiwsir']>>> b*7['qiwsir', 'qiwsir', 'qiwsir', 'qiwsir', 'qiwsir', 'qiwsir', 'qiwsir']
对于此类数据,下面一些操作是类似的:
>>> first = "hello,world">>> welcome_str'Welcome you'>>> first+","+welcome_str #用+号连接str'hello,world,Welcome you'>>> welcome_str #原来的str没有受到影响,即上面的+号连接后从新生成了一个字符串'Welcome you'>>> first'hello,world'>>> language = ['python']>>> git_list['qiwsir', 'github', 'io']>>> language + git_list #用+号连接list,得到一个新的list['python', 'qiwsir', 'github', 'io']>>> git_list['qiwsir', 'github', 'io']>>> language['python']>>> len(welcome_str) #得到字符数11>>> len(git_list) #得到元素数3
区别
list和str的最大区别是:list是原处可以改变的,str则原处不可变。这个怎么理解呢?
首先看对list的这些操作,其特点是在原处将list进行了修改:
>>> git_list['qiwsir', 'github', 'io']>>> git_list.append("python")>>> git_list['qiwsir', 'github', 'io', 'python']>>> git_list[1] 'github'>>> git_list[1] = 'github.com'>>> git_list['qiwsir', 'github.com', 'io', 'python']>>> git_list.insert(1,"algorithm")>>> git_list['qiwsir', 'algorithm', 'github.com', 'io', 'python']>>> git_list.pop()'python'>>> del git_list[1]>>> git_list['qiwsir', 'github.com', 'io']
以上这些操作,如果用在str上,都会报错,比如:
>>> welcome_str'Welcome you'>>> welcome_str[1] = 'E'Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: 'str' object does not support item assignment>>> del welcome_str[1]Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: 'str' object doesn't support item deletion>>> welcome_str.append("E")Traceback (most recent call last):File "<stdin>", line 1, in <module>AttributeError: 'str' object has no attribute 'append'
新闻热点
疑难解答