第一:变量
变量作用:保存状态:说白了,程序运行的状态就是状态的变化,变量是用来保存状态的,变量值的不断变化就产生了运行程序的最终输出结果
一:声明变量
# -*-coding:utf-8-*- name = 'cyy'
上述代码声明了一个变量,变量名为: name,变量(name)的值为:"cyy"
二:变量的定义规则
- 变量名只能是 字母、数字或下划线的任意组合
- 变量名的第一个字符不能是数字(是字母或下划线(_))
- 大小写敏感
- 两种风格:conn_obj或ConnObj
- 不能使用关键字,不能使用内建
以下关键字不能声明为变量名
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
注:变量全部大写的一般是常量
三:变量赋值
链式赋值:y=x=z=1
多元赋值:x,y=1,2 x,y=y,x
增量/减量/乘量/除量 赋值:
变量解压赋值:
第二:数据类型
数据类型:数据类型是在数据结构中的定义是一个值的集合以及定义在这个值集上的一组操作。
python使用对象模型来存储数据,每一个数据类型都有一个内置的类,每新建一个数据,实际就是在初始化生成一个对象,即所有数据都是对象
对象三个特性
- 身份:内存地址,可以用id()获取
- 类型:决定了该对象可以保存什么类型值,可执行何种操作,需遵循什么规则,可用type()获取
- 值:对象保存的真实数据
以下是标准的数据类型:
一:数字
1:整型(int)
python2.*与python3.*关于整型的区
python2.*
在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
1 class int(object): 2 """ 3 int(x=0) -> int or long 4 int(x, base=10) -> int or long 5 6 Convert a number or string to an integer, or return 0 if no arguments 7 are given. If x is floating point, the conversion truncates towards zero. 8 If x is outside the integer range, the function returns a long instead. 9 10 If x is not a number or if base is given, then x must be a string or 11 Unicode object representing an integer literal in the given base. The 12 literal can be preceded by '+' or '-' and be surrounded by whitespace. 13 The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to 14 interpret the base from the string as an integer literal. 15 >>> int('0b100', base=0) 16 """ 17 def bit_length(self): 18 """ 返回表示该数字的时占用的最少位数 """ 19 """ 20 int.bit_length() -> int 21 22 Number of bits necessary to represent self in binary. 23 >>> bin(37) 24 '0b100101' 25 >>> (37).bit_length() 26 """ 27 return 0 28 29 def conjugate(self, *args, **kwargs): # real signature unknown 30 """ 返回该复数的共轭复数 """ 31 """ Returns self, the complex conjugate of any int. """ 32 pass 33 34 def __abs__(self): 35 """ 返回绝对值 """ 36 """ x.__abs__() <==> abs(x) """ 37 pass 38 39 def __add__(self, y): 40 """ x.__add__(y) <==> x+y """ 41 pass 42 43 def __and__(self, y): 44 """ x.__and__(y) <==> x&y """ 45 pass 46 47 def __cmp__(self, y): 48 """ 比较两个数大小 """ 49 """ x.__cmp__(y) <==> cmp(x,y) """ 50 pass 51 52 def __coerce__(self, y): 53 """ 强制生成一个元组 """ 54 """ x.__coerce__(y) <==> coerce(x, y) """ 55 pass 56 57 def __divmod__(self, y): 58 """ 相除,得到商和余数组成的元组 """ 59 """ x.__divmod__(y) <==> divmod(x, y) """ 60 pass 61 62 def __div__(self, y): 63 """ x.__div__(y) <==> x/y """ 64 pass 65 66 def __float__(self): 67 """ 转换为浮点类型 """ 68 """ x.__float__() <==> float(x) """ 69 pass 70 71 def __floordiv__(self, y): 72 """ x.__floordiv__(y) <==> x//y """ 73 pass 74 75 def __format__(self, *args, **kwargs): # real signature unknown 76 pass 77 78 def __getattribute__(self, name): 79 """ x.__getattribute__('name') <==> x.name """ 80 pass 81 82 def __getnewargs__(self, *args, **kwargs): # real signature unknown 83 """ 内部调用 __new__方法或创建对象时传入参数使用 """ 84 pass 85 86 def __hash__(self): 87 """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。""" 88 """ x.__hash__() <==> hash(x) """ 89 pass 90 91 def __hex__(self): 92 """ 返回当前数的 十六进制 表示 """ 93 """ x.__hex__() <==> hex(x) """ 94 pass 95 96 def __index__(self): 97 """ 用于切片,数字无意义 """ 98 """ x[y:z] <==> x[y.__index__():z.__index__()] """ 99 pass 100 101 def __init__(self, x, base=10): # known special case of int.__init__ 102 """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 103 """ 104 int(x=0) -> int or long 105 int(x, base=10) -> int or long 106 107 Convert a number or string to an integer, or return 0 if no arguments 108 are given. If x is floating point, the conversion truncates towards zero. 109 If x is outside the integer range, the function returns a long instead. 110 111 If x is not a number or if base is given, then x must be a string or 112 Unicode object representing an integer literal in the given base. The 113 literal can be preceded by '+' or '-' and be surrounded by whitespace. 114 The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to 115 interpret the base from the string as an integer literal. 116 >>> int('0b100', base=0) 117 # (copied from class doc) 118 """ 119 pass 120 121 def __int__(self): 122 """ 转换为整数 """ 123 """ x.__int__() <==> int(x) """ 124 pass 125 126 def __invert__(self): 127 """ x.__invert__() <==> ~x """ 128 pass 129 130 def __long__(self): 131 """ 转换为长整数 """ 132 """ x.__long__() <==> long(x) """ 133 pass 134 135 def __lshift__(self, y): 136 """ x.__lshift__(y) <==> x<<y """ 137 pass 138 139 def __mod__(self, y): 140 """ x.__mod__(y) <==> x%y """ 141 pass 142 143 def __mul__(self, y): 144 """ x.__mul__(y) <==> x*y """ 145 pass 146 147 def __neg__(self): 148 """ x.__neg__() <==> -x """ 149 pass 150 151 @staticmethod # known case of __new__ 152 def __new__(S, *more): 153 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 154 pass 155 156 def __nonzero__(self): 157 """ x.__nonzero__() <==> x != 0 """ 158 pass 159 160 def __oct__(self): 161 """ 返回改值的 八进制 表示 """ 162 """ x.__oct__() <==> oct(x) """ 163 pass 164 165 def __or__(self, y): 166 """ x.__or__(y) <==> x|y """ 167 pass 168 169 def __pos__(self): 170 """ x.__pos__() <==> +x """ 171 pass 172 173 def __pow__(self, y, z=None): 174 """ 幂,次方 """ 175 """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ 176 pass 177 178 def __radd__(self, y): 179 """ x.__radd__(y) <==> y+x """ 180 pass 181 182 def __rand__(self, y): 183 """ x.__rand__(y) <==> y&x """ 184 pass 185 186 def __rdivmod__(self, y): 187 """ x.__rdivmod__(y) <==> divmod(y, x) """ 188 pass 189 190 def __rdiv__(self, y): 191 """ x.__rdiv__(y) <==> y/x """ 192 pass 193 194 def __repr__(self): 195 """转化为解释器可读取的形式 """ 196 """ x.__repr__() <==> repr(x) """ 197 pass 198 199 def __str__(self): 200 """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式""" 201 """ x.__str__() <==> str(x) """ 202 pass 203 204 def __rfloordiv__(self, y): 205 """ x.__rfloordiv__(y) <==> y//x """ 206 pass 207 208 def __rlshift__(self, y): 209 """ x.__rlshift__(y) <==> y<<x """ 210 pass 211 212 def __rmod__(self, y): 213 """ x.__rmod__(y) <==> y%x """ 214 pass 215 216 def __rmul__(self, y): 217 """ x.__rmul__(y) <==> y*x """ 218 pass 219 220 def __ror__(self, y): 221 """ x.__ror__(y) <==> y|x """ 222 pass 223 224 def __rpow__(self, x, z=None): 225 """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ 226 pass 227 228 def __rrshift__(self, y): 229 """ x.__rrshift__(y) <==> y>>x """ 230 pass 231 232 def __rshift__(self, y): 233 """ x.__rshift__(y) <==> x>>y """ 234 pass 235 236 def __rsub__(self, y): 237 """ x.__rsub__(y) <==> y-x """ 238 pass 239 240 def __rtruediv__(self, y): 241 """ x.__rtruediv__(y) <==> y/x """ 242 pass 243 244 def __rxor__(self, y): 245 """ x.__rxor__(y) <==> y^x """ 246 pass 247 248 def __sub__(self, y): 249 """ x.__sub__(y) <==> x-y """ 250 pass 251 252 def __truediv__(self, y): 253 """ x.__truediv__(y) <==> x/y """ 254 pass 255 256 def __trunc__(self, *args, **kwargs): 257 """ 返回数值被截取为整形的值,在整形中无意义 """ 258 pass 259 260 def __xor__(self, y): 261 """ x.__xor__(y) <==> x^y """ 262 pass 263 264 denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 265 """ 分母 = 1 """ 266 """the denominator of a rational number in lowest terms""" 267 268 imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 269 """ 虚数,无意义 """ 270 """the imaginary part of a complex number""" 271 272 numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 273 """ 分子 = 数字大小 """ 274 """the numerator of a rational number in lowest terms""" 275 276 real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 277 """ 实属,无意义 """ 278 """the real part of a complex number""" 279 280 int
python3.*整形长度无限制
1 class int(object): 2 """ 3 int(x=0) -> integer 4 int(x, base=10) -> integer 5 6 Convert a number or string to an integer, or return 0 if no arguments 7 are given. If x is a number, return x.__int__(). For floating point 8 numbers, this truncates towards zero. 9 10 If x is not a number or if base is given, then x must be a string, 11 bytes, or bytearray instance representing an integer literal in the 12 given base. The literal can be preceded by '+' or '-' and be surrounded 13 by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. 14 Base 0 means to interpret the base from the string as an integer literal. 15 >>> int('0b100', base=0) 16 """ 17 def bit_length(self): # real signature unknown; restored from __doc__ 18 """ 返回表示该数字的时占用的最少位数 """ 19 """ 20 int.bit_length() -> int 21 22 Number of bits necessary to represent self in binary. 23 >>> bin(37) 24 '0b100101' 25 >>> (37).bit_length() 26 """ 27 return 0 28 29 def conjugate(self, *args, **kwargs): # real signature unknown 30 """ 返回该复数的共轭复数 """ 31 """ Returns self, the complex conjugate of any int. """ 32 pass 33 34 @classmethod # known case 35 def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 36 """ 37 int.from_bytes(bytes, byteorder, *, signed=False) -> int 38 39 Return the integer represented by the given array of bytes. 40 41 The bytes argument must be a bytes-like object (e.g. bytes or bytearray). 42 43 The byteorder argument determines the byte order used to represent the 44 integer. If byteorder is 'big', the most significant byte is at the 45 beginning of the byte array. If byteorder is 'little', the most 46 significant byte is at the end of the byte array. To request the native 47 byte order of the host system, use `sys.byteorder' as the byte order value. 48 49 The signed keyword-only argument indicates whether two's complement is 50 used to represent the integer. 51 """ 52 pass 53 54 def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 55 """ 56 int.to_bytes(length, byteorder, *, signed=False) -> bytes 57 58 Return an array of bytes representing an integer. 59 60 The integer is represented using length bytes. An OverflowError is 61 raised if the integer is not representable with the given number of 62 bytes. 63 64 The byteorder argument determines the byte order used to represent the 65 integer. If byteorder is 'big', the most significant byte is at the 66 beginning of the byte array. If byteorder is 'little', the most 67 significant byte is at the end of the byte array. To request the native 68 byte order of the host system, use `sys.byteorder' as the byte order value. 69 70 The signed keyword-only argument determines whether two's complement is 71 used to represent the integer. If signed is False and a negative integer 72 is given, an OverflowError is raised. 73 """ 74 pass 75 76 def __abs__(self, *args, **kwargs): # real signature unknown 77 """ abs(self) """ 78 pass 79 80 def __add__(self, *args, **kwargs): # real signature unknown 81 """ Return self+value. """ 82 pass 83 84 def __and__(self, *args, **kwargs): # real signature unknown 85 """ Return self&value. """ 86 pass 87 88 def __bool__(self, *args, **kwargs): # real signature unknown 89 """ self != 0 """ 90 pass 91 92 def __ceil__(self, *args, **kwargs): # real signature unknown 93 """ 94 整数返回自己 95 如果是小数 96 math.ceil(3.1)返回4 97 """ 98 """ Ceiling of an Integral returns itself. """ 99 pass 100 101 def __divmod__(self, *args, **kwargs): # real signature unknown 102 """ 相除,得到商和余数组成的元组 """ 103 """ Return divmod(self, value). """ 104 pass 105 106 def __eq__(self, *args, **kwargs): # real signature unknown 107 """ Return self==value. """ 108 pass 109 110 def __float__(self, *args, **kwargs): # real signature unknown 111 """ float(self) """ 112 pass 113 114 def __floordiv__(self, *args, **kwargs): # real signature unknown 115 """ Return self//value. """ 116 pass 117 118 def __floor__(self, *args, **kwargs): # real signature unknown 119 """ Flooring an Integral returns itself. """ 120 pass 121 122 def __format__(self, *args, **kwargs): # real signature unknown 123 pass 124 125 def __getattribute__(self, *args, **kwargs): # real signature unknown 126 """ Return getattr(self, name). """ 127 pass 128 129 def __getnewargs__(self, *args, **kwargs): # real signature unknown 130 pass 131 132 def __ge__(self, *args, **kwargs): # real signature unknown 133 """ Return self>=value. """ 134 pass 135 136 def __gt__(self, *args, **kwargs): # real signature unknown 137 """ Return self>value. """ 138 pass 139 140 def __hash__(self, *args, **kwargs): # real signature unknown 141 """ Return hash(self). """ 142 pass 143 144 def __index__(self, *args, **kwargs): # real signature unknown 145 """ 用于切片,数字无意义 """ 146 """ Return self converted to an integer, if self is suitable for use as an index into a list. """ 147 pass 148 149 def __init__(self, x, base=10): # known special case of int.__init__ 150 """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 151 """ 152 int(x=0) -> integer 153 int(x, base=10) -> integer 154 155 Convert a number or string to an integer, or return 0 if no arguments 156 are given. If x is a number, return x.__int__(). For floating point 157 numbers, this truncates towards zero. 158 159 If x is not a number or if base is given, then x must be a string, 160 bytes, or bytearray instance representing an integer literal in the 161 given base. The literal can be preceded by '+' or '-' and be surrounded 162 by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. 163 Base 0 means to interpret the base from the string as an integer literal. 164 >>> int('0b100', base=0) 165 # (copied from class doc) 166 """ 167 pass 168 169 def __int__(self, *args, **kwargs): # real signature unknown 170 171 """ int(self) """ 172 pass 173 174 def __invert__(self, *args, **kwargs): # real signature unknown 175 """ ~self """ 176 pass 177 178 def __le__(self, *args, **kwargs): # real signature unknown 179 """ Return self<=value. """ 180 pass 181 182 def __lshift__(self, *args, **kwargs): # real signature unknown 183 """ Return self<<value. """ 184 pass 185 186 def __lt__(self, *args, **kwargs): # real signature unknown 187 """ Return self<value. """ 188 pass 189 190 def __mod__(self, *args, **kwargs): # real signature unknown 191 """ Return self%value. """ 192 pass 193 194 def __mul__(self, *args, **kwargs): # real signature unknown 195 """ Return self*value. """ 196 pass 197 198 def __neg__(self, *args, **kwargs): # real signature unknown 199 """ -self """ 200 pass 201 202 @staticmethod # known case of __new__ 203 def __new__(*args, **kwargs): # real signature unknown 204 """ Create and return a new object. See help(type) for accurate signature. """ 205 pass 206 207 def __ne__(self, *args, **kwargs): # real signature unknown 208 """ Return self!=value. """ 209 pass 210 211 def __or__(self, *args, **kwargs): # real signature unknown 212 """ Return self|value. """ 213 pass 214 215 def __pos__(self, *args, **kwargs): # real signature unknown 216 """ +self """ 217 pass 218 219 def __pow__(self, *args, **kwargs): # real signature unknown 220 """ Return pow(self, value, mod). """ 221 pass 222 223 def __radd__(self, *args, **kwargs): # real signature unknown 224 """ Return value+self. """ 225 pass 226 227 def __rand__(self, *args, **kwargs): # real signature unknown 228 """ Return value&self. """ 229 pass 230 231 def __rdivmod__(self, *args, **kwargs): # real signature unknown 232 """ Return divmod(value, self). """ 233 pass 234 235 def __repr__(self, *args, **kwargs): # real signature unknown 236 """ Return repr(self). """ 237 pass 238 239 def __rfloordiv__(self, *args, **kwargs): # real signature unknown 240 """ Return value//self. """ 241 pass 242 243 def __rlshift__(self, *args, **kwargs): # real signature unknown 244 """ Return value<<self. """ 245 pass 246 247 def __rmod__(self, *args, **kwargs): # real signature unknown 248 """ Return value%self. """ 249 pass 250 251 def __rmul__(self, *args, **kwargs): # real signature unknown 252 """ Return value*self. """ 253 pass 254 255 def __ror__(self, *args, **kwargs): # real signature unknown 256 """ Return value|self. """ 257 pass 258 259 def __round__(self, *args, **kwargs): # real signature unknown 260 """ 261 Rounding an Integral returns itself. 262 Rounding with an ndigits argument also returns an integer. 263 """ 264 pass 265 266 def __rpow__(self, *args, **kwargs): # real signature unknown 267 """ Return pow(value, self, mod). """ 268 pass 269 270 def __rrshift__(self, *args, **kwargs): # real signature unknown 271 """ Return value>>self. """ 272 pass 273 274 def __rshift__(self, *args, **kwargs): # real signature unknown 275 """ Return self>>value. """ 276 pass 277 278 def __rsub__(self, *args, **kwargs): # real signature unknown 279 """ Return value-self. """ 280 pass 281 282 def __rtruediv__(self, *args, **kwargs): # real signature unknown 283 """ Return value/self. """ 284 pass 285 286 def __rxor__(self, *args, **kwargs): # real signature unknown 287 """ Return value^self. """ 288 pass 289 290 def __sizeof__(self, *args, **kwargs): # real signature unknown 291 """ Returns size in memory, in bytes """ 292 pass 293 294 def __str__(self, *args, **kwargs): # real signature unknown 295 """ Return str(self). """ 296 pass 297 298 def __sub__(self, *args, **kwargs): # real signature unknown 299 """ Return self-value. """ 300 pass 301 302 def __truediv__(self, *args, **kwargs): # real signature unknown 303 """ Return self/value. """ 304 pass 305 306 def __trunc__(self, *args, **kwargs): # real signature unknown 307 """ Truncating an Integral returns itself. """ 308 pass 309 310 def __xor__(self, *args, **kwargs): # real signature unknown 311 """ Return self^value. """ 312 pass 313 314 denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 315 """the denominator of a rational number in lowest terms""" 316 317 imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 318 """the imaginary part of a complex number""" 319 320 numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 321 """the numerator of a rational number in lowest terms""" 322 323 real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 324 """the real part of a complex number""" 325 326 python3.5
2:长整形(long)
python2.*:
跟C语言不同,Python的长整型没有指定位宽,也就是说Python没有限制长整型数值的大小,但是实际上由于机器内存有限,所以我们使用的长整型数值不可能无限大。在使用过程中,我们如何区分长整型和整型数值呢?通常的做法是在数字尾部加上一个大写字母L或小写字母l以表示该整数是长整型的,例如:a = 9223372036854775808L注意,自从Python2起,如果发生溢出,Python会自动将整型数据转换为长整型,所以如今在长整型数据后面不加字母L也不会导致严重后果了。
python3.*:
长整型,整型统一归为整型
3:布尔型(bool)
真(True)或假(False)
4:浮点数
浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,一个浮点数的小数点位置是可变的,比如,1.23x109和12.3x108是完全相等的。浮点数可以用数学写法,如1.23
,3.14
,-9.01
,等等。但是对于很大或很小的浮点数,就必须用科学计数法表示,把10用e替代,1.23x109就是1.23e9
,或者12.3e8
,0.000012可以写成1.2e-5
,等等。
整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的,而浮点数运算则可能会有四舍五入的误差
5:复数
复数由实数部分和虚数部分组成,一般形式为x+yj,其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数。(虚数部分的字母j大小写都可以)
>>> 1.3 + 2.5j == 1.3 + 2.5J True
6:与数字有关的内置函数
二:字符串
定义:它是一个有序的字符的集合,用于存储和表示基本的文本信息,‘’或“”或‘’‘ ’‘’中间包含的内容称之为字符串
特性:
只能存放一个值
不可变
按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序
1:字符串创建
a='hello word'
2:字符串的常用方法
name="zzl" print(name.capitalize())#首字母变成大写 print(name.center(30)) # 居中 print(name.center(30,'*'))#居中加填充 msg='hello world' print(msg.count('l'))#统计出现l在msg中出现的次数 print(msg.count('l',0,3))#统计l在msg中0到3之间l出现的次数 print(msg.count('l',-1))#统计l在msg中最后一个字符中出现l的次数 print(msg.endswith('s'))#判断msg是不是以s结尾,不是则为False,是为True print(msg.startswith('h'))#判断msg是不是以h开头,不是则为False,是为True print(msg.find('l'))#统计l出现的位置,如果不存在,则返回-1,存在返回位置,存在多个,只返回第一个出现的位置 print(msg.find('l',3,9))#统计l在msg的3到9之间,l出现的位置 print(msg.index('e'))#index与find本质区别是:index已经知道msg中存在e,然后进行查找,如果不存在会报错。 print(msg.isdigit())#判断字符串中是否包含数字,包含数字为False,不包含为True msg='hello world'#多用于字符串拼接 msg_new='*'.join(msg) print(msg_new) msg='root:x:0:0:root:/bin/bash' print(msg.split(':')) #split分割 print(msg.split(':',maxsplit=1))#以:为分割符,最大分割一次 msg_list=msg.split(':') print(':'.join(msg_list))#按照:拼接字符串 msg='helLo world' print(msg.upper())#小写转化为大写 print(msg.swapcase())#大小写转换 print(msg.lower()) #大写转换为小写 msg='*****zzl*****' print(msg.strip('*'))#去掉首尾的指定字符 print(msg.lstrip('*'))#去除左边指定字符 print(msg.rstrip('*'))#去除右边指定字符 print(msg.replace('z','y')) #替换字符,不指定个数全部替换,指定几个就替换几个 print(msg.replace('z','y',1)) #字符串拼接 msg='My name is {name}, age : {age} ' print(msg.format(name='zzl',age=18)) print(msg.format_map({'name':'zzl','age':18}))
3:字符串不常用的方法
#不常用的方法 msg='hello world' print(msg.isalpha())#msg是纯字母返回True,不是则返回False print(msg.isidentifier())#msg是内置标识符,返回True,否则返回False print(msg.isspace())#msg是空格,返回True,反之,返回False print(msg.istitle())#msg是标题,也就是首字母大写,返回True print(msg.ljust(10))#10个字符左对齐 print(msg.ljust(10,'*'))#10个字符左对齐,10个字符*填充 print(msg.rjust(10))#10个字符右对齐 print(msg.rjust(10,'*'))#10个字符右对齐,10个字符*填充 print(msg.zfill(20))#总长度20个,不足则在右边添加0 message='''aaa bbb ccc ddd ''' print(message.splitlines()) #按照行数切分
msg='hello' #字符串索引操作 print(msg[4]) print(msg[-2]) #字符串的切分操作 print(msg[0:3]) #切分原则:顾头不顾尾 print(msg[0:]) print(msg[:3]) print(msg[0:2000:2])#按两个字符切分 print(msg[::-1])#hello倒过来 #再看变量解压操作 msg='hello' x,y,z,*_=msg print(x) print(y) print(z) x,y,z='abc','aaa','xxx' print(x) print(y) print(z)
4:字符串工厂函数
class str(object): """ str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'. """ def capitalize(self): # real signature unknown; restored from __doc__ """ 首字母变大写 S.capitalize() -> str Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. """ return "" def casefold(self): # real signature unknown; restored from __doc__ """ S.casefold() -> str Return a version of S suitable for caseless comparisons. """ return "" def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ 原来字符居中,不够用空格补全 S.center(width[, fillchar]) -> str Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) """ return "" def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ 从一个范围内的统计某str出现次数 S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__ """ encode(encoding='utf-8',errors='strict') 以encoding指定编码格式编码,如果出错默认报一个ValueError,除非errors指定的是 ignore或replace S.encode(encoding='utf-8', errors='strict') -> bytes Encode S using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors. """ return b"" def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. """ return False def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__ """ 将字符串中包含的 转换成tabsize个空格 S.expandtabs(tabsize=8) -> str Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ return "" def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def format(self, *args, **kwargs): # known special case of str.format """ 格式化输出 三种形式: 形式一. >>> print('{0}{1}{0}'.format('a','b')) aba 形式二:(必须一一对应) >>> print('{}{}{}'.format('a','b')) Traceback (most recent call last): File "<input>", line 1, in <module> IndexError: tuple index out of range >>> print('{}{}'.format('a','b')) ab 形式三: >>> print('{name} {age}'.format(age=12,name='lhf')) lhf 12 S.format(*args, **kwargs) -> str Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ pass def format_map(self, mapping): # real signature unknown; restored from __doc__ """ 与format区别 '{name}'.format(**dict(name='alex')) '{name}'.format_map(dict(name='alex')) S.format_map(mapping) -> str Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}'). """ return "" def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.index(sub[, start[, end]]) -> int Like S.find() but raise ValueError when the substring is not found. """ return 0 def isalnum(self): # real signature unknown; restored from __doc__ """ 至少一个字符,且都是字母或数字才返回True S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise. """ return False def isalpha(self): # real signature unknown; restored from __doc__ """ 至少一个字符,且都是字母才返回True S.isalpha() -> bool Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise. """ return False def isdecimal(self): # real signature unknown; restored from __doc__ """ S.isdecimal() -> bool Return True if there are only decimal characters in S, False otherwise. """ return False def isdigit(self): # real signature unknown; restored from __doc__ """ S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise. """ return False def isidentifier(self): # real signature unknown; restored from __doc__ """ 字符串为关键字返回True S.isidentifier() -> bool Return True if S is a valid identifier according to the language definition. Use keyword.iskeyword() to test for reserved identifiers such as "def" and "class". """ return False def islower(self): # real signature unknown; restored from __doc__ """ 至少一个字符,且都是小写字母才返回True S.islower() -> bool Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise. """ return False def isnumeric(self): # real signature unknown; restored from __doc__ """ S.isnumeric() -> bool Return True if there are only numeric characters in S, False otherwise. """ return False def isprintable(self): # real signature unknown; restored from __doc__ """ S.isprintable() -> bool Return True if all characters in S are considered printable in repr() or S is empty, False otherwise. """ return False def isspace(self): # real signature unknown; restored from __doc__ """ 至少一个字符,且都是空格才返回True S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise. """ return False def istitle(self): # real signature unknown; restored from __doc__ """ >>> a='Hello' >>> a.istitle() True >>> a='HellP' >>> a.istitle() False S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. """ return False def isupper(self): # real signature unknown; restored from __doc__ """ S.isupper() -> bool Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise. """ return False def join(self, iterable): # real signature unknown; restored from __doc__ """ #对序列进行操作(分别使用' '与':'作为分隔符) >>> seq1 = ['hello','good','boy','doiido'] >>> print ' '.join(seq1) hello good boy doiido >>> print ':'.join(seq1) hello:good:boy:doiido #对字符串进行操作 >>> seq2 = "hello good boy doiido" >>> print ':'.join(seq2) h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o #对元组进行操作 >>> seq3 = ('hello','good','boy','doiido') >>> print ':'.join(seq3) hello:good:boy:doiido #对字典进行操作 >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4} >>> print ':'.join(seq4) boy:good:doiido:hello #合并目录 >>> import os >>> os.path.join('/hello/','good/boy/','doiido') '/hello/good/boy/doiido' S.join(iterable) -> str Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """ return "" def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.ljust(width[, fillchar]) -> str Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). """ return "" def lower(self): # real signature unknown; restored from __doc__ """ S.lower() -> str Return a copy of the string S converted to lowercase. """ return "" def lstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.lstrip([chars]) -> str Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def maketrans(self, *args, **kwargs): # real signature unknown """ Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result. """ pass def partition(self, sep): # real signature unknown; restored from __doc__ """ 以sep为分割,将S分成head,sep,tail三部分 S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. """ pass def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ """ S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ return "" def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rfind(sub[, start[, end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rindex(sub[, start[, end]]) -> int Like S.rfind() but raise ValueError when the substring is not found. """ return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.rjust(width[, fillchar]) -> str Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space). """ return "" def rpartition(self, sep): # real signature unknown; restored from __doc__ """ S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S. """ pass def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ """ S.rsplit(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified, any whitespace string is a separator. """ return [] def rstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.rstrip([chars]) -> str Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ """ 以sep为分割,将S切分成列表,与partition的区别在于切分结果不包含sep, 如果一个字符串中包含多个sep那么maxsplit为最多切分成几部分 >>> a='a,b c d e' >>> a.split() ['a,b', 'c', 'd', 'e'] S.split(sep=None, maxsplit=-1) -> list of strings Return a list of the words in 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. """ return [] def splitlines(self, keepends=None): # real signature unknown; restored from __doc__ """ Python splitlines() 按照行(' ', ' ', ')分隔, 返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如 果为 True,则保留换行符。 >>> x 'adsfasdf sadf asdf adf' >>> x.splitlines() ['adsfasdf', 'sadf', 'asdf', 'adf'] >>> x.splitlines(True) ['adsfasdf ', 'sadf ', 'asdf ', 'adf'] S.splitlines([keepends]) -> list of strings Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. """ return False def strip(self, chars=None): # real signature unknown; restored from __doc__ """ S.strip([chars]) -> str Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def swapcase(self): # real signature unknown; restored from __doc__ """ 大小写反转 S.swapcase() -> str Return a copy of S with uppercase characters converted to lowercase and vice versa. """ return "" def title(self): # real signature unknown; restored from __doc__ """ S.title() -> str Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case. """ return "" def translate(self, table): # real signature unknown; restored from __doc__ """ table=str.maketrans('alex','big SB') a='hello abc' print(a.translate(table)) S.translate(table) -> str Return a copy of the string S in which each character has been mapped through the given translation table. The table must implement lookup/indexing via __getitem__, for instance a dictionary or list, mapping Unicode ordinals to Unicode ordinals, strings, or None. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted. """ return "" def upper(self): # real signature unknown; restored from __doc__ """ S.upper() -> str Return a copy of S converted to uppercase. """ return "" def zfill(self, width): # real signature unknown; restored from __doc__ """ 原来字符右对齐,不够用0补齐 S.zfill(width) -> str Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. """ return "" def __add__(self, *args, **kwargs): # real signature unknown """ Return self+value. """ pass def __contains__(self, *args, **kwargs): # real signature unknown """ Return key in self. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __format__(self, format_spec): # real signature unknown; restored from __doc__ """ S.__format__(format_spec) -> str Return a formatted version of S as described by format_spec. """ return "" def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getitem__(self, *args, **kwargs): # real signature unknown """ Return self[key]. """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ pass def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__ """ str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'. # (copied from class doc) """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass def __mod__(self, *args, **kwargs): # real signature unknown """ Return self%value. """ pass def __mul__(self, *args, **kwargs): # real signature unknown """ Return self*value.n """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __rmod__(self, *args, **kwargs): # real signature unknown """ Return value%self. """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __str__(self, *args, **kwargs): # real signature unknown """ Return str(self). """ pass
三:列表
定义:内以逗号分隔,按照索引,存放各种数据类型,每个位置代表一个元素
特性:
1.可存放多个值
2.可修改指定索引位置对应的值,可变
3.按照从左到右的顺序定义列表元素,下标从0开始顺序访问,有序
1:列表的创建
name_list=['zzl','cyy','zl','cy']
或
name_list=list('zzl')
或
name=list([’zzl','cyy'])
2:列表的常用方法
name_list=['zzl','cyy','zl','cy'] #列表的索引操作 print(name_list[-1]) print(name_list[0:2]) print(name_list[::-1]) #列表的内置方法 #append增加到末尾 name_list=['zzl','cyy','zl','cy'] name_list.append('yy') print(name_list) #insert插入到指定位置 name_list=['zzl','cyy','zl','cy'] name_list.insert(0,'ylqh') print(name_list) #pop删除name_list.pop()#默认从右边删除 name_list.pop(2)#指定删除第二个 print(name_list) #清空列表 name_list=['zzl','cyy','zl','cy'] name_list.clear() print(name_list) #复制一份copy name_list=['zzl','cyy','zl','cy'] i=name_list.copy() print(i) #计数 name_list=['zzl','cyy','zl','yy','cy','yy'] print(name_list.count('yy'))#yy出现了几次 #两个列表合并 name_list=['zzl','cyy','zl','cy'] nlist=['ylqi','lift'] name_list.extend(nlist) print(name_list) #单独加入列表 every_lis='xxx' name_list.extend(every_lis) print(name_list) #remove移除 name_list=['zzl','cyy','zl','cy'] name_list.remove('zl')#按照元素名移除,有多个重复的元素值时,移除第一个 print(name_list) #reverse反序排列
name_list=['zzl','cyy','zl','cy'] name_list.reverse()#反序 print(name_list) #sort排列 name_list=['d','c','A','1','@','*'] name_list.sort()#按照字符编码表排列 print(name_list) #统计列表有几个元素或说成列表的长度 name_list=['zzl','cyy','zl','cy'] print(len(name_list))#统计长度 #判断是否在列表里面 # name_list=['zzl','cyy','zl','cy'] print ('zl' in name_list) print ('l' in name_list)
3:列表工厂函数
class list(object): """ list() -> new empty list list(iterable) -> new list initialized from iterable's items """ def append(self, p_object): # real signature unknown; restored from __doc__ """ L.append(object) -> None -- append object to end """ pass def clear(self): # real signature unknown; restored from __doc__ """ L.clear() -> None -- remove all items from L """ pass def copy(self): # real signature unknown; restored from __doc__ """ L.copy() -> list -- a shallow copy of L """ return [] def count(self, value): # real signature unknown; restored from __doc__ """ L.count(value) -> integer -- return number of occurrences of value """ return 0 def extend(self, iterable): # real signature unknown; restored from __doc__ """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """ pass def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. """ return 0 def insert(self, index, p_object): # real signature unknown; restored from __doc__ """ L.insert(index, object) -- insert object before index """ pass def pop(self, index=None): # real signature unknown; restored from __doc__ """ L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range. """ pass def remove(self, value): # real signature unknown; restored from __doc__ """ L.remove(value) -> None -- remove first occurrence of value. Raises ValueError if the value is not present. """ pass def reverse(self): # real signature unknown; restored from __doc__ """ L.reverse() -- reverse *IN PLACE* """ pass def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__ """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """ pass def __add__(self, *args, **kwargs): # real signature unknown """ Return self+value. """ pass def __contains__(self, *args, **kwargs): # real signature unknown """ Return key in self. """ pass def __delitem__(self, *args, **kwargs): # real signature unknown """ Delete self[key]. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __iadd__(self, *args, **kwargs): # real signature unknown """ Implement self+=value. """ pass def __imul__(self, *args, **kwargs): # real signature unknown """ Implement self*=value. """ pass def __init__(self, seq=()): # known special case of list.__init__ """ list() -> new empty list list(iterable) -> new list initialized from iterable's items # (copied from class doc) """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass def __mul__(self, *args, **kwargs): # real signature unknown """ Return self*value.n """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __reversed__(self): # real signature unknown; restored from __doc__ """ L.__reversed__() -- return a reverse iterator over the list """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass def __setitem__(self, *args, **kwargs): # real signature unknown """ Set self[key] to value. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ L.__sizeof__() -- size of L in memory, in bytes """ pass __hash__ = None
四:元组
定义:与列表差不多,只不过[]改成(),同时也叫作只读列表
特性:
1.可以存多个值
2.不可变
3.按照从左到右的顺序定义元组元素,下标从0开始顺序访问,有序
1:元组的创建
msg = (1,2,3,4,5) #或者 msg = tuple((1,2,3,4,5,6))
2:元组的常用方法
t=('zzl','cyy',123) print(t.count('cyy'))#统计cyy的次数 print(t.index('cyy'))#统计cyy的索引,没有则报错 print(len(t))#统计元组的长度 print('cyy' in t) #包含,t是否包含cyy
3:元组的工厂函数
lass tuple(object): """ tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. """ def count(self, value): # real signature unknown; restored from __doc__ """ T.count(value) -> integer -- return number of occurrences of value """ return 0 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ T.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. """ return 0 def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, seq=()): # known special case of tuple.__init__ """ tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ T.__sizeof__() -- size of T in memory, in bytes """ pass
4:元组的不可变行eg
t = ('zzl', 'cyy', ['ZZL', 'CYY']) print(t) t[2][0] = 'L' t[2][1] = 'Y' print(t) 输出信息: ('zzl', 'cyy', ['ZZL', 'CYY']) ('zzl', 'cyy', ['L', 'Y'])
#这个tuple定义的时候有三个元素,为zzl,cyy还有一个列表,说好的元组不可变,怎么发生变化了呢?
#下面分析一下哦
表面上看,tuple的元素确实变了,但其实变的不是tuple的元素,而是list的元素。tuple一开始指向的list并没有改成别的list,所以,tuple所谓的不变是说,tuple的每个元素,指向永远不变。即指向'zzl',就不能改成指向'cyy',指向一个list,就不能改成指向其他对象,但指向的这个list本身是可变的!
理解了“指向不变”后,要创建一个内容也不变的tuple怎么做?
那就必须保证tuple的每一个元素本身也不能变。
五:字典
定义:{key:value},key-value 形式,key必须可hash
特性:
1.可存放多个值
2.可修改指定key对应的值,可变
3.无序
4.可变类型不能当做字典的key,value可以是任何数据类型
5.key不能重复
1:字典的创建
dic={'name1':'zzl','name2':'cyy'} 或者 dic1={(1,2,3):'aa'} #元组可以当做key 或者 dic2 = dict(name='zzl', age=18) 或者 dic3 = dict({"name": "zzl", 'age': 20}) 或者 dic4 = dict((['name','zzl'],['age',16])) 输出结果: {'name1': 'zzl', 'name2': 'cyy'} {(1, 2, 3): 'aa'} {'name': 'zzl', 'age': 18} {'name': 'zzl', 'age': 20} {'name': 'zzl', 'age': 16}
2:字典的常用方法
取值: info={'msg1':'zzl','msg2':'cyy','msg3':'zl','msg4':'yy'} print('msg1' in info) #标准用法,存在返回True,不存在返回False print(info.get('msg2')) #获取 print(info['msg2']) #获取的到的时候,取值 print(list(info.keys()))#获取所有的key值 print(list(info.values()))#获取所有的value值 print(list(info.items()))#获取所有的数值 print(info['msg8'])#一旦获取不到,则报错 输出结果: True cyy cyy ['msg1', 'msg2', 'msg3', 'msg4'] ['zzl', 'cyy', 'zl', 'yy'] [('msg1', 'zzl'), ('msg2', 'cyy'), ('msg3', 'zl'), ('msg4', 'yy')] Traceback (most recent call last): File "G:/迎领启航/python_code/week2/day2/dic.py", line 13, in <module> print(info['msg8'])#一旦获取不到,则报错 KeyError: 'msg8' #增加 info={'msg1':'zzl','msg2':'cyy'} print(info) info['msg3'] = 'zl'#增加 print(info) 结果: {'msg1': 'zzl', 'msg2': 'cyy'} {'msg1': 'zzl', 'msg2': 'cyy', 'msg3': 'zl'} #修改: info={'msg1':'zzl','msg2':'cyy'} print(info) info['msg2'] = 'yy' #修改 print(info) 结果: {'msg1': 'zzl', 'msg2': 'cyy'} {'msg1': 'zzl', 'msg2': 'yy'} 一下五个都为删除用法: info={'msg1':'zzl','msg2':'cyy','msg3':'zl','msg4':'yy'} print(info) info.pop('msg3') print(info) del info['msg2'] print(info) info.popitem()# 随机删除一个 print(info) info.clear() #整个列表清空 print(info)
del info #删除整个字典 结果: {'msg1': 'zzl', 'msg2': 'cyy', 'msg3': 'zl', 'msg4': 'yy'} {'msg1': 'zzl', 'msg2': 'cyy', 'msg4': 'yy'} {'msg1': 'zzl', 'msg4': 'yy'} {'msg1': 'zzl'} {}
3.字典的其他操作:
多级字典嵌套:
dict_name = { "msg1":{ "name1": ["张","occupy"], "name2": ["成","my baby"], }, "msg2":{ "name3":["迎","my dear"] }, "msg3":{ "name4":["胜","success"] } } dict_name["msg2"]["name3"][1] += ",亲爱的" print(dict_name["msg2"]["name3"]) 输出结果: ['迎', 'my dear,亲爱的']
其他用法汇总:
dic=dict.fromkeys(['host1','host2','host3'],['test1','test2']) print(dic) #{'host1': ['test1', 'test2'], 'host2': ['test1', 'test2'], 'host3': ['test1', 'test2']} dic['host2'][1]='test3' print(dic) #{'host1': ['test1', 'test3'], 'host2': ['test1', 'test3'], 'host3': ['test1', 'test3']}
info={'name1':'zzl','name2':'cyy','name3':'yy'} print(info) #取出所有的key: print(info.keys()) #取出所有的value: print(info.values()) 结果: {'name1': 'zzl', 'name2': 'cyy', 'name3': 'yy'} dict_keys(['name1', 'name2', 'name3']) dict_values(['zzl', 'cyy', 'yy']) #update info1={'name1':'zzl','name2':'cyy'} print(info1) info2={'name1':'zl','name3':'yy'} print(info2) info1.update(info2) print(info1) 结果: #把info1有的覆盖,没有的追加 {'name1': 'zzl', 'name2': 'cyy'} {'name1': 'zl', 'name3': 'yy'} {'name1': 'zl', 'name2': 'cyy', 'name3': 'yy'} #setdefault info={'name1':'zzl','name2':'cyy','name3':'yy'} info.setdefault('name4','zl')#info[name4]='zl' print(info) info.setdefault('name1','occupy') #注意看了,name1没有发生变化哦 print(info) info.setdefault('hobby',[]).append('study') info.setdefault('hobby',[]).append('play') print(info) 结果: {'name1': 'zzl', 'name2': 'cyy', 'name3': 'yy', 'name4': 'zl'} {'name1': 'zzl', 'name2': 'cyy', 'name3': 'yy', 'name4': 'zl'} {'name1': 'zzl', 'name2': 'cyy', 'name3': 'yy', 'name4': 'zl', 'hobby': ['study', 'play']}
4:字典的工厂函数
class dict(object): """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) """ def clear(self): # real signature unknown; restored from __doc__ """ 清除内容 """ """ D.clear() -> None. Remove all items from D. """ pass def copy(self): # real signature unknown; restored from __doc__ """ 浅拷贝 """ """ D.copy() -> a shallow copy of D """ pass @staticmethod # known case def fromkeys(S, v=None): # real signature unknown; restored from __doc__ """ dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ """ 根据key获取值,d是默认值 """ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def has_key(self, k): # real signature unknown; restored from __doc__ """ 是否有key """ """ D.has_key(k) -> True if D has a key k, else False """ return False def items(self): # real signature unknown; restored from __doc__ """ 所有项的列表形式 """ """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ return [] def iteritems(self): # real signature unknown; restored from __doc__ """ 项可迭代 """ """ D.iteritems() -> an iterator over the (key, value) items of D """ pass def iterkeys(self): # real signature unknown; restored from __doc__ """ key可迭代 """ """ D.iterkeys() -> an iterator over the keys of D """ pass def itervalues(self): # real signature unknown; restored from __doc__ """ value可迭代 """ """ D.itervalues() -> an iterator over the values of D """ pass def keys(self): # real signature unknown; restored from __doc__ """ 所有的key列表 """ """ D.keys() -> list of D's keys """ return [] def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ 获取并在字典中移除 """ """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ """ 获取并在字典中移除 """ """ D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """ """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update """ 更新 {'name':'alex', 'age': 18000} [('name','sbsbsb'),] """ """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass def values(self): # real signature unknown; restored from __doc__ """ 所有的值 """ """ D.values() -> list of D's values """ return [] def viewitems(self): # real signature unknown; restored from __doc__ """ 所有项,只是将内容保存至view对象中 """ """ D.viewitems() -> a set-like object providing a view on D's items """ pass def viewkeys(self): # real signature unknown; restored from __doc__ """ D.viewkeys() -> a set-like object providing a view on D's keys """ pass def viewvalues(self): # real signature unknown; restored from __doc__ """ D.viewvalues() -> an object providing a view on D's values """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __contains__(self, k): # real signature unknown; restored from __doc__ """ D.__contains__(k) -> True if D has a key k, else False """ return False def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ D.__sizeof__() -> size of D in memory, in bytes """ pass __hash__ = None
六:集合
定义:由不同元素组成的集合,集合中是一组无序排列的可hash值,可以作为字典的key
集合是一个无序的,不重复的数据组合,它的主要作用如下:
特性:
无序的,不重复的数据组合
去重,把一个列表变成集合,就自动去重了
关系测试,测试两组数据之前的交集、差集、并集等关系
1:集合的创建
msg = set([1,2,3])#创建一个数值的集合 print(msg) 或者 msg = set("hello")#创建一个唯一字符的集合 print(msg) 输出结果: {1, 2, 3} {'h', 'e', 'o', 'l'}
2:集合的常用操作
msg = set([1, 1, 2, 2, 3, 3])#重复的元素自动过滤掉 print(msg) 结果: {1, 2, 3} msg.add(8) #可以添加元素到set中,可以重复添加,但是没有任何效果哦 print(msg) 结果: {8, 1, 2, 3} msg.remove(1)#删除set中的元素 print(msg) 结果: {8, 2, 3} msg.update([5,8,6])#在set中添加多项 print(msg) 结果: {2, 3, 5, 6, 8} print(len(msg))#set的长度 结果: 5
set关系运算
msg1 = set([2, 3, 5, 6, 8]) msg2 = set([1,3,5]) print(1 in msg1) #测试1是否是msg1的成员,是则返回True,否则返回False 输出结果: False print(1 not in msg1) #测试1是否不是msg1的成员,是则返回False,不是返回True 输出结果: True #测试是否msg2中的每一个元素都在msg1中 print(msg2.issubset(msg1)) print(msg2 <= msg1) 输出结果: False False #测试msg1中的每个元素都在msg2中 print(msg2.issuperset(msg1)) print(msg2 >= msg1) 输出结果: False False #返回一个新的set包含msg1和msg2的每一个元素 print(msg2.union(msg1)) print(msg2 | msg1) 输出结果: {1, 2, 3, 5, 6, 8} {1, 2, 3, 5, 6, 8} #返回一个新的set包含msg1与msg2的公共元素 print(msg2.intersection(msg1)) print(msg1 & msg2) 输出结果: {3, 5} {3, 5} #返回一个新的set包含msg2中有但是msg1中没有的元素 print(msg2.difference(msg1)) print(msg2 - msg1) 输出结果: {1} {1} #返回一个新的set包含msg2和msg1中不重复的元素 print(msg2.symmetric_difference(msg1)) print(msg2 ^ msg1) 输出结果: {1, 2, 6, 8} {1, 2, 6, 8} #返回set “msg1”的一个浅的复制 print(msg1.copy()) 输出结果: {8, 2, 3, 5, 6}
set做交集、并集等操作
msg1 = set([1,3,5]) msg2 = set([1,2,3]) print(msg1 & msg2) #msg1与msg2的交集 print(msg1| msg2 ) #msg1与msg2的并集 print(msg1 - msg2) #求差集(元素在msg1中,但不在msg2中) print(msg1 ^ msg2) #对称差集(元素在msg1或msg2中,但不会同时出现在二者中) 输出结果: {1, 3} {1, 2, 3, 5} {5} {2, 5}
3:集合工厂
class set(object): """ set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. """ def add(self, *args, **kwargs): # real signature unknown """ Add an element to a set. This has no effect if the element is already present. """ pass def clear(self, *args, **kwargs): # real signature unknown """ Remove all elements from this set. """ pass def copy(self, *args, **kwargs): # real signature unknown """ Return a shallow copy of a set. """ pass def difference(self, *args, **kwargs): # real signature unknown """ 相当于s1-s2 Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.) """ pass def difference_update(self, *args, **kwargs): # real signature unknown """ Remove all elements of another set from this set. """ pass def discard(self, *args, **kwargs): # real signature unknown """ 与remove功能相同,删除元素不存在时不会抛出异常 Remove an element from a set if it is a member. If the element is not a member, do nothing. """ pass def intersection(self, *args, **kwargs): # real signature unknown """ 相当于s1&s2 Return the intersection of two sets as a new set. (i.e. all elements that are in both sets.) """ pass def intersection_update(self, *args, **kwargs): # real signature unknown """ Update a set with the intersection of itself and another. """ pass def isdisjoint(self, *args, **kwargs): # real signature unknown """ Return True if two sets have a null intersection. """ pass def issubset(self, *args, **kwargs): # real signature unknown """ 相当于s1<=s2 Report whether another set contains this set. """ pass def issuperset(self, *args, **kwargs): # real signature unknown """ 相当于s1>=s2 Report whether this set contains another set. """ pass def pop(self, *args, **kwargs): # real signature unknown """ Remove and return an arbitrary set element. Raises KeyError if the set is empty. """ pass def remove(self, *args, **kwargs): # real signature unknown """ Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """ pass def symmetric_difference(self, *args, **kwargs): # real signature unknown """ 相当于s1^s2 Return the symmetric difference of two sets as a new set. (i.e. all elements that are in exactly one of the sets.) """ pass def symmetric_difference_update(self, *args, **kwargs): # real signature unknown """ Update a set with the symmetric difference of itself and another. """ pass def union(self, *args, **kwargs): # real signature unknown """ 相当于s1|s2 Return the union of sets as a new set. (i.e. all elements that are in either set.) """ pass def update(self, *args, **kwargs): # real signature unknown """ Update a set with the union of itself and others. """ pass def __and__(self, *args, **kwargs): # real signature unknown """ Return self&value. """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __iand__(self, *args, **kwargs): # real signature unknown """ Return self&=value. """ pass def __init__(self, seq=()): # known special case of set.__init__ """ set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. # (copied from class doc) """ pass def __ior__(self, *args, **kwargs): # real signature unknown """ Return self|=value. """ pass def __isub__(self, *args, **kwargs): # real signature unknown """ Return self-=value. """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __ixor__(self, *args, **kwargs): # real signature unknown """ Return self^=value. """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __or__(self, *args, **kwargs): # real signature unknown """ Return self|value. """ pass def __rand__(self, *args, **kwargs): # real signature unknown """ Return value&self. """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Return state information for pickling. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __ror__(self, *args, **kwargs): # real signature unknown """ Return value|self. """ pass def __rsub__(self, *args, **kwargs): # real signature unknown """ Return value-self. """ pass def __rxor__(self, *args, **kwargs): # real signature unknown """ Return value^self. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __sub__(self, *args, **kwargs): # real signature unknown """ Return self-value. """ pass def __xor__(self, *args, **kwargs): # real signature unknown """ Return self^value. """ pass __hash__ = None
七:总结
1.按存值个数区分
标量/原子类型 | 数字,字符串 |
容器类型 | 列表,元组,字典 |
2.按可变不可变区分
可变 | 列表,字典 |
不可变 | 数字,字符串,元组 |
证明:可变/不可变
更改数据类型其中的元素,如果内存地址发生变化,则为不可变类型,如果内存地址没有发生变化,则为可变类型。
详情参考:http://www.cnblogs.com/ylqh/p/6388330.html 的内存管理
3.按访问顺序区分
直接访问 | 数字 |
顺序访问(序列类型) | 字符串,列表,元组 |
key值访问(映射类型) | 字典 |
补充:字典占用的内存空间比列表大,(因为要在内存空间保存一端时间的hash表)但是字典查询速度比列表快,联想到非关系型数据库比关系型数据查询要快。
循环区别:
字符串循环:
#字符串循环: 方法1: msg='love' for i in msg: print(i) 结果: l o v e 方法2: for i in enumerate(msg): print(i) 结果: (0, 'l') (1, 'o') (2, 'v') (3, 'e') 方法3:倒叙循环 for i in msg[::-1]: print(i)
列表循环:
lis=['zzl','cyy','yy'] for i in lis: print(i) for i in enumerate(lis): print(i) 结果: zzl cyy yy (0, 'zzl') (1, 'cyy') (2, 'yy')
元组循环:
tup=('x','y','z') for i in tup: print(i) for i in enumerate(tup): print(i) 结果: x y z (0, 'x') (1, 'y') (2, 'z')
字典循环:
#字典循环 info={'msg1':'zzl','msg2':'cyy','msg3':'zl','msg4':'yy'} #方法1 for key in info: print(key,info[key]) 结果 msg1 zzl msg2 cyy msg3 zl msg4 yy #方法2 for k,v in info.items(): #会先把dict转成list,数据大时最好不要用 print(k,v) 结果: msg1 zzl msg2 cyy msg3 zl msg4 yy info={'name1':'zzl','name2':'cyy','name3':'yy'} 方法3: info={'name1':'zzl','name2':'cyy','name3':'yy'} for i in enumerate(info): print(i) 结果: (0, 'name1') (1, 'name2') (2, 'name3') 方法4: for i in info.keys(): print(i,info[i]) 结果: name1 zzl name2 cyy name3 yy 方法5: for v in info.values(): print(v) 结果: zzl cyy yy
数据类型转换内置函数汇总:
字符串、列表、字典、元组之间的相互转换:
字符串转为其他类型:
#字符串转换为元组 msg='cyy' print(tuple(msg),type(tuple(msg))) 结果: ('c', 'y', 'y') <class 'tuple'> #字符串转换为列表 print(list(msg),type(list(msg))) 结果: ['c', 'y', 'y'] <class 'list'> #字符串转换为字典 msg='{"name":"cyy","age":18}' print(type(msg)) print(eval(msg),type(eval(msg))) 结果: <class 'str'> {'name': 'cyy', 'age': 18} <class 'dict'>
列表转为其他类型:
列表不可以转为字典
nums=[1,3,5,7,8,0] #列表转为字符串: print(str(nums),type(str(nums))) 结果: [1, 3, 5, 7, 8, 0] <class 'str'> #列表转为元组: print(tuple(nums),type(tuple(nums))) 结果: (1, 3, 5, 7, 8, 0) <class 'tuple'>
元组转为其他类型:
元组不可以转为字典
tup=(1, 2, 3, 4, 5) #元组转为字符串 print(tup.__str__(),type(tup.__str__())) 结果: (1, 2, 3, 4, 5) <class 'str'> #元组转为列表 print(list(tup),type(list(tup))) 结果: [1, 2, 3, 4, 5] <class 'list'>
字典转为其他类型:
dic = {'name': 'Zara', 'age': 7, 'class': 'First'} #字典转为字符串 print(str(dic),type(str(dic))) 结果: {'age': 7, 'name': 'Zara', 'class': 'First'} <class 'str'> #字典可以转为元组 print(tuple(dic),type(tuple(dic))) #字典可以转为元组 print(tuple(dic.values()),type(tuple(dic.values()))) 结果: ('age', 'name', 'class') <class 'tuple'> (7, 'Zara', 'First') <class 'tuple'> #字典转为列表 print(list(dic),type(list(dic))) #字典转为列表 print(list(dic.values()),type(list(dic.values()))) 结果: ['age', 'name', 'class'] <class 'list'> [7, 'Zara', 'First'] <class 'list'>
msg='My name is {name}, age : {age} '
print(msg.format(name='zzl',age=18))
print(msg.format_map({'name':'zzl','age':18}))