list 和 str
list 和 str 两种类型数据,有不少相似的地方,也有很大的区别。本讲对她们做个简要比较,同时也是对前面有关两者的知识复习一下,所谓“温故而知新”。
相同点
都属于序列类型的数据
所谓序列类型的数据,就是说它的每一个元素都可以通过指定一个编号,行话叫做“偏移量”的方式得到,而要想一次得到多个元素,可以使用切片。偏移量从 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'
如果要修改一个 str,不得不这样。
>>> welcome_str
'Welcome you'
>>> welcome_str[0]+"E"+welcome_str[2:] #从新生成一个 str
'WElcome you'
>>> welcome_str #对原来的没有任何影响
'Welcome you'
其实,在这种做法中,相当于重新生成了一个 str。
多维 list
这个也应该算是两者的区别了,虽然有点牵强。在 str 中,里面的每个元素只能是字符,在 list 中,元素可以是任何类型的数据。前面见的多是数字或者字符,其实还可以这样:
>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> matrix[0][1]
2
>>> mult = [[1,2,3],['a','b','c'],'d','e']
>>> mult
[[1, 2, 3], ['a', 'b', 'c'], 'd', 'e']
>>> mult[1][1]
'b'
>>> mult[2]
'd'
以上显示了多维 list 以及访问方式。在多维的情况下,里面的 list 被当成一个元素对待。
list 和 str 转化
以下涉及到的 split()和 join()在前面字符串部分已经见过。一回生,二回熟,这次再见面,特别是在已经学习了列表的基础上,应该有更深刻的理解。
str.split()
这个内置函数实现的是将 str 转化为 list。其中 str=""是分隔符。
在看例子之前,请看官在交互模式下做如下操作:
>>>help(str.split)
得到了对这个内置函数的完整说明。特别强调:这是一种非常好的学习方法
split(...) S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.
不管是否看懂上面这段话,都可以看例子。还是希望看官能够理解上面的内容。
>>> line = "Hello.I am qiwsir.Welcome you."
>>> line.split(".") #以英文的句点为分隔符,得到 list
['Hello', 'I am qiwsir', 'Welcome you', '']
>>> line.split(".",1) #这个 1,就是表达了上文中的:If maxsplit is given, at most maxsplit splits are done.
['Hello', 'I am qiwsir.Welcome you.']
>>> name = "Albert Ainstain" #也有可能用空格来做为分隔符
>>> name.split(" ")
['Albert', 'Ainstain']
下面的例子,让你更有点惊奇了。
>>> s = "I am, writing\npython\tbook on line" #这个字符串中有空格,逗号,换行\n,tab 缩进\t 符号
>>> print s #输出之后的样式
I am, writing
python book on line
>>> s.split() #用 split(),但是括号中不输入任何参数
['I', 'am,', 'writing', 'Python', 'book', 'on', 'line']
如果 split()不输入任何参数,显示就是见到任何分割符号,就用其分割了。
"[sep]".join(list)
join 可以说是 split 的逆运算,举例:
>>> name
['Albert', 'Ainstain']
>>> "".join(name) #将 list 中的元素连接起来,但是没有连接符,表示一个一个紧邻着
'AlbertAinstain'
>>> ".".join(name) #以英文的句点做为连接分隔符
'Albert.Ainstain'
>>> " ".join(name) #以空格做为连接的分隔符
'Albert Ainstain'
回到上面那个神奇的例子中,可以这么使用 join.
>>> s = "I am, writing\npython\tbook on line"
>>> print s
I am, writing
python book on line
>>> s.split()
['I', 'am,', 'writing', 'Python', 'book', 'on', 'line']
>>> " ".join(s.split()) #重新连接,不过有一点遗憾,am 后面逗号还是有的。怎么去掉?
'I am, writing python book on line'
list 和 str的更多相关文章
- [转]Python中的str与unicode处理方法
早上被python的编码搞得抓耳挠腮,在搜资料的时候感觉这篇博文很不错,所以收藏在此. python2.x中处理中文,是一件头疼的事情.网上写这方面的文章,测次不齐,而且都会有点错误,所以在这里打算自 ...
- python中的str,unicode和gb2312
实例1: v1=u '好神奇的问题!?' type(v1)->unicode v1.decode("utf-8")# not work,because v1 is unico ...
- LDR、STR指令
LDR(load register)指令将内存内容加载入通用寄存器 STR(store register)指令将寄存器内容存入内存空间中 #define GPJ0CON 0xE0200240 _sta ...
- Python之str()与repr()的区别
Python之str()与repr()的区别 str()一般是将数值转成字符串,主要面向用户. repr()是将一个对象转成字符串显示,注意只是显示用,有些对象转成字符串没有直接的意思.如list, ...
- 判断一个字符串str不为空的方法
1.str == null; 2."".equals(str); 3.str.length 4.str.isEmpty(); 注意:length是属性,一般集合类对象拥有的属性,取 ...
- python 3.5: TypeError: a bytes-like object is required, not 'str'
出现该错误往往是通过open()函数打开文本文件时,使用了'rb'属性,如:fileHandle=open(filename,'rb'),则此时是通过二进制方式打开文件的,所以在后面处理时如果使用了s ...
- django 在字符串[str(list)]中精确查找
1.问题描述 1.1表结构 1.2问题 ref_list为id列表的字符串,需要从ref_list中找出包含指定id的数据(eg id=8).如果实用models.objects.filter(ref ...
- Python基本数据类型——str
字符串常用操作 移除空白 分割 长度 索引 切片 class str(basestring): """ str(object='') -> string Retur ...
- Python_Day_02 str内部方法总结
刚开始学习Python,看了一天的字符串内部方法,现在来总结一下. capitalize(self) 将一句话的首字母变大写,其他字母都变小 name = "love PyThon" ...
- Python字符串str的方法使用
#!usr/bin/env python# -*-coding:utf-8-*-#字符串通常用双引号或单引号来表示:'123',"abc","字符串"#str字 ...
随机推荐
- Android中Adapter之BaseAdapter使用
Android界面中有时候需要显示稍微复杂的界面时,就需要我们自定义一个adapter,而此adapter就要继承BaseAdapter,重新其中的方法. Android中Adapte ...
- spring,hibernate,struts的面试笔试题
1 Action是不是线程安全的?如果不是 有什么方式可以保证Action的线程安全?如果是,说明原因不是声明局部变量,或者扩展RequestProcessor,让每次都创建一个Action,或者在s ...
- AC日记——codevs 1688 求逆序对
1688 求逆序对 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold 题解 查看运行结果 题目描述 Description 给定一个序列a1,a2,…, ...
- request模块提交数据
http://ctf8.shiyanbar.com/jia/ #coding:utf-8import re,requestsurl = r"http://ctf8.shiyanbar.com ...
- VS2013无法启动 IIS Express Web解决办法
不要勾选[覆盖应用程序根URL(U)],或让[覆盖应用程序根URL(U)]下面的输入框和上面的输入框的地址一样! 使用VS2013有一段时间了,因前期都是编写C/S程序,没有使用到B/S调试器.前几日 ...
- win7系统电脑连接小米蓝牙音箱
一.买好蓝牙适配器,插到电脑上. 二.右下角工具栏找到蓝牙图标 三.右键这个图标,选择'显示Bluetooth设备' 四.找到小米蓝牙音箱 'NDZ-030-AA' 五.双击打开它,然后选择'服务'选 ...
- usb驱动开发3之先看core
上节中看到usb目录中有一个core目录,凡是认识这个core单词的人都会想要先看看它是什么,对不?用LDD3中一幅图,来表述usb core所处地位. usb core负责实现一些核心的功能,为别的 ...
- The Skyline Problem
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city whe ...
- [转]SIFT特征提取分析
SIFT(Scale-invariant feature transform)是一种检测局部特征的算法,该算法通过求一幅图中的特征点(interest points,or corner points) ...
- 在opencv3中实现机器学习之:利用正态贝叶斯分类
opencv3.0版本中,实现正态贝叶斯分类器(Normal Bayes Classifier)分类实例 #include "stdafx.h" #include "op ...